Chapter 1
Data Structure and Algorithms
PU BCA past exam questions
Past questions and answers
75 questions set from this chapter, 3 of them more than once; 1 is most repeated (set, or a close variant set, in 3 or more exams). Most repeated first.
- Most repeated · 3 of 6 exams
- Asked 3 times
- 2025 Spring · 5 marks
- 2024 Fall · 5 marks
- 2024 Spring · 5 marks
Write short notes on: B-tree
Answer
B-tree
A B-tree of order is a balanced multiway search tree designed for data stored on disks, where each node is read in one block access. Properties:
- Every node has at most children and keys.
- Every non-root internal node has at least children; the root has at least 2 children (unless it is a leaf).
- A node with children holds keys, stored in sorted order, and the keys separate the ranges of its subtrees.
- All leaves are at the same level, so the tree is perfectly balanced.
Operations
- Search: like a BST but with a multiway choice at each node; .
- Insertion: insert the key in the proper leaf; if the leaf overflows (more than keys) split it around the median and push the median key up to the parent. Splits may propagate up and the tree grows at the root, so height increases only when the root splits.
- Deletion: remove the key; if a node has too few keys, borrow from a sibling or merge with it.
Because of the large branching factor the height is small, , so very few disk accesses are needed.
Uses: database indexes and file systems. A variant, the B+ tree, keeps all data in the linked leaves.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2024 Fall · 5 marks
- 2023 Spring · 5 marks
Write short notes on: Divide and conquer
Answer
Divide and conquer is an algorithm design technique that solves a problem by breaking it into smaller subproblems of the same type, solving them (usually recursively), and combining their solutions.
Steps
- Divide: split the problem into two or more smaller independent subproblems.
- Conquer: solve each subproblem recursively; if it is small enough, solve it directly (base case).
- Combine: merge the sub-solutions to get the solution of the original problem.
Example: Merge sort
MergeSort(A, low, high)
if low < high
mid = (low + high) / 2
MergeSort(A, low, mid)
MergeSort(A, mid+1, high)
Merge(A, low, mid, high)
Recurrence: , which solves to .
Other examples: binary search, quicksort, Strassen's matrix multiplication, Tower of Hanoi.
Advantages: simple, natural recursive solutions, efficient algorithms, suited to parallel execution. Disadvantages: recursion overhead and stack space.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2023 Spring · 8 marks
- 2022 Fall · 7 marks
Define minimum spanning tree? Find the minimal spanning tree of the following graph using Kruskal's algorithm. (Weighted graph given in the paper with vertices 0 to 6 and edges 0-1:7, 0-3:5, 1-2:8, 1-3:9, 1-4:7, 2-4:5, 3-4:15, 3-5:6, 4-5:8, 4-6:9, 5-6:11.)
Answer
Minimum spanning tree. A minimum spanning tree (MST) of a connected, weighted, undirected graph is a subset of edges that connects all vertices without any cycle and has the minimum possible total weight. For vertices it has exactly edges.
Kruskal's algorithm. Sort all edges by weight; take edges in increasing order and add an edge if it does not form a cycle with the edges already chosen (checked with union-find), until edges are chosen.
Sorted edges: 0-3 (5), 2-4 (5), 3-5 (6), 0-1 (7), 1-4 (7), 1-2 (8), 4-5 (8), 1-3 (9), 4-6 (9), 5-6 (11), 3-4 (15).
| Edge | Weight | Decision | Components after |
|---|---|---|---|
| 0-3 | 5 | accept | {0,3} |
| 2-4 | 5 | accept | {0,3}, {2,4} |
| 3-5 | 6 | accept | {0,3,5}, {2,4} |
| 0-1 | 7 | accept | {0,1,3,5}, {2,4} |
| 1-4 | 7 | accept | {0,1,2,3,4,5} |
| 1-2 | 8 | reject (cycle) | |
| 4-5 | 8 | reject (cycle) | |
| 1-3 | 9 | reject (cycle) | |
| 4-6 | 9 | accept | {0,1,2,3,4,5,6} |
Six edges have been chosen for 7 vertices, so we stop.
MST edges: 0-3, 2-4, 3-5, 0-1, 1-4, 4-6.
Total weight = .
Complexity: , dominated by sorting the edges.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Convert following infix expression to postfix using stack.
Similar questions: Stack operations, infix to postfix (2022 Fall)
Answer
Rules used
Operands go straight to the output. Operator precedence: ^ (highest, right-associative), then , then . Before pushing an operator, pop from the stack every operator of higher precedence (or equal precedence for left-associative ones). ( is pushed; on ) pop until (.
Expression:
| Symbol | Stack (bottom to top) | Output |
|---|---|---|
| A | A | |
| + | + | A |
| B | + | A B |
| * | + * | A B |
| ( | + * ( | A B |
| C | + * ( | A B C |
| ^ | + * ( ^ | A B C |
| D | + * ( ^ | A B C D |
| - | + * ( - (pop ^) | A B C D ^ |
| E | + * ( - | A B C D ^ E |
| ) | + * (pop -, remove () | A B C D ^ E - |
| ^ | + * ^ (^ is higher than *) | A B C D ^ E - |
| ( | + * ^ ( | A B C D ^ E - |
| F | + * ^ ( | A B C D ^ E - F |
| + | + * ^ ( + | A B C D ^ E - F |
| G | + * ^ ( + | A B C D ^ E - F G |
| * | + * ^ ( + * | A B C D ^ E - F G |
| H | + * ^ ( + * | A B C D ^ E - F G H |
| ) | + * ^ (pop * and +) | A B C D ^ E - F G H * + |
| - | - (pop ^, *, + first) | A B C D ^ E - F G H * + ^ * + |
| I | - | A B C D ^ E - F G H * + ^ * + I |
| end | (pop -) | A B C D ^ E - F G H * + ^ * + I - |
Postfix expression:
that is ABCD^E-FGH*+^*+I-.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
What is Time Complexity and Space Complexity? Explain different types of asymptotic notations with proper diagram.
Similar questions: Time and space complexity, asymptotic notations (2023 Spring)
Answer
Time complexity is the amount of time an algorithm takes to run, expressed as a function of the input size (in practice, the number of basic operations). Space complexity is the amount of memory the algorithm needs as a function of , including the input, auxiliary variables and the recursion stack. For example, a single loop summing numbers has time and space .
Asymptotic notations describe the growth of a running time for large .
1. Big-O (upper bound). if there are constants , such that for all . It is used for the worst case.
cost
| c*g(n)
| / .
| / . f(n)
| / .
| / .
|/.______________ n
n0
(f(n) stays below c*g(n) after n0)
2. Big-Omega (lower bound). if for all . It is used for the best case.
cost
| f(n)
| . .
| . .
| . c*g(n)
|.______________ n
n0
(f(n) stays above c*g(n) after n0)
3. Big-Theta (tight bound). if there are constants and such that for all . It means is both and .
cost
| c2*g(n)
| /
| / f(n) (between the two curves)
| /
| / c1*g(n)
|/______________ n
n0
4. Little-o and little-omega are strict bounds: means grows strictly slower than , and means strictly faster.
Example: . Then for , so ; , so ; hence .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 8 marks
Define Time and Space Complexity. Explain different types of asymptotic notations with examples.
Similar questions: Time and space complexity, asymptotic notations (2024 Spring)
Answer
Time complexity of an algorithm is the amount of time it takes as a function of the input size (the number of basic operations executed). Space complexity is the total memory it needs as a function of : the space for the input plus auxiliary space (variables, recursion stack, temporary arrays). For example, linear search has time and space ; merge sort has time and space .
Asymptotic notations describe the growth rate of a function for large , ignoring constants and lower-order terms.
-
Big-O, (upper bound, worst case). if there exist constants and such that for all . Example: . Since for , .
-
Big-Omega, (lower bound, best case). if for all . Example: for all , so .
-
Big-Theta, (tight bound). if for all , i.e. both and . Example: for , so .
-
Little-o, (strict upper bound): for every . Example: .
-
Little-omega, (strict lower bound). Example: .
Common order of growth: .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
What is stack? Explain the basic operations on stack. Convert the following infix expression to postfix .
Similar questions: Infix to postfix A+B*(C^D-E)^(F+G*H)-I (2025 Spring)
Answer
Stack. A stack is a linear data structure in which insertion and deletion take place only at one end, the top, following the LIFO (Last In, First Out) rule.
Basic operations
push(x): add element on the top; if the stack is full, overflow occurs.pop(): remove and return the top element; if the stack is empty, underflow occurs.peek()(top): read the top element without removing it.isEmpty(): true if the stack has no element.isFull(): true if no more elements can be pushed (array implementation).
All of them take time.
Infix to postfix:
Scan left to right: operands go to the output; operators go on the stack after popping operators of higher or equal precedence (* and / have higher precedence than + and -, and are left associative); ( is pushed and ) pops until (.
| Symbol | Stack | Output |
|---|---|---|
| ( | ( | |
| a | ( | a |
| + | ( + | a |
| b | ( + | a b |
| ) | a b + | |
| * | * | a b + |
| ( | * ( | a b + |
| c | * ( | a b + c |
| - | * ( - | a b + c |
| d | * ( - | a b + c d |
| ) | * | a b + c d - |
| / | / (pop * first) | a b + c d - * |
| ( | / ( | a b + c d - * |
| e | / ( | a b + c d - * e |
| + | / ( + | a b + c d - * e |
| f | / ( + | a b + c d - * e f |
| ) | / | a b + c d - * e f + |
| end | a b + c d - * e f + / |
Postfix expression:
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Why is the study of Data Structures and Algorithms essential as a discipline? Additionally, define an algorithm and mention its key characteristics. What is the time complexity of the code below in worst case scenario?
int a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
}
int a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
}
Answer
Why study Data Structures and Algorithms
- Every program stores data and processes it. The way data is organised decides how fast and how economically operations (search, insert, delete, sort) can be done.
- A good choice of data structure and algorithm reduces running time and memory; for large inputs the difference between and is the difference between a program that finishes and one that does not.
- It gives reusable building blocks (stack, queue, list, tree, graph, hash table) used in compilers, operating systems, databases, networks and AI.
- It develops problem-solving and analytical skills, and lets us compare solutions by measurable cost instead of guesswork.
- It is the foundation of later subjects and of technical interviews.
Algorithm
An algorithm is a finite, well-defined sequence of unambiguous steps that takes zero or more inputs and produces at least one output to solve a problem.
Key characteristics:
- Input: zero or more well-defined inputs.
- Output: at least one result.
- Definiteness: each step is clear and unambiguous.
- Finiteness: it terminates after a finite number of steps.
- Effectiveness: each step is basic enough to be carried out exactly in finite time.
- Correctness / generality: it gives the right result for every valid input.
Time complexity of the code
The outer loop runs for . For a given the inner loop runs for , which is times. Total executions of the statement:
The count does not depend on data values, so the worst case time complexity is (quadratic).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
Explain Divide & Conquer and Dynamic Programming approaches. Illustrate your answer with suitable algorithmic examples.
Answer
Divide and Conquer
A problem is solved in three steps:
- Divide the problem into smaller sub-problems of the same type.
- Conquer each sub-problem recursively (solve directly when small enough).
- Combine the sub-solutions into the solution of the original problem.
The sub-problems are independent (they do not overlap). Its running time is usually described by a recurrence .
Example: Merge sort
MergeSort(A, low, high)
if low < high
mid = (low + high) / 2
MergeSort(A, low, mid) // conquer left
MergeSort(A, mid + 1, high) // conquer right
Merge(A, low, mid, high) // combine in O(n)
, so . Other examples: quick sort, binary search ().
Dynamic Programming
Dynamic programming solves problems whose sub-problems overlap and which have optimal substructure (an optimal solution contains optimal solutions of its sub-problems). Each sub-problem is solved only once and its result is stored in a table (memoization, top-down, or tabulation, bottom-up) and reused.
Example: Fibonacci numbers
Plain recursion fib(n) = fib(n-1) + fib(n-2) recomputes the same values and takes . With a table:
Fib(n)
F[0] = 0; F[1] = 1
for i = 2 to n
F[i] = F[i-1] + F[i-2]
return F[n]
Time , space . Other examples: 0/1 knapsack, longest common subsequence, matrix-chain multiplication, Floyd-Warshall.
Comparison
| Divide and Conquer | Dynamic Programming |
|---|---|
| Sub-problems are independent | Sub-problems overlap |
| Usually top-down recursion | Top-down (memo) or bottom-up |
| Sub-results are not stored | Sub-results stored in a table |
| Merge sort, quick sort, binary search | Knapsack, LCS, Fibonacci |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Write a recursive algorithm to solve the Tower of Hanoi problem for 'n' disks. Explain how recursion and stack are related in this context.
Answer
Tower of Hanoi
There are disks of different sizes on peg A (source). Move all to peg C (destination) using peg B (auxiliary), moving one disk at a time and never placing a larger disk on a smaller one.
Recursive algorithm
Hanoi(n, source, aux, dest)
if n == 1
print "Move disk 1 from source to dest"
return
Hanoi(n-1, source, dest, aux) // move n-1 disks out of the way
print "Move disk n from source to dest"
Hanoi(n-1, aux, source, dest) // bring them onto disk n
C version:
#include <stdio.h>
void hanoi(int n, char s, char a, char d) {
if (n == 1) { printf("Move disk 1 from %c to %c\n", s, d); return; }
hanoi(n - 1, s, d, a);
printf("Move disk %d from %c to %c\n", n, s, d);
hanoi(n - 1, a, s, d);
}
int main() { hanoi(3, 'A', 'B', 'C'); return 0; }
For the moves are: A to C, A to B, C to B, A to C, B to A, B to C, A to C. The number of moves satisfies , so
Recursion and stack
Each recursive call pushes an activation record (stack frame) onto the system call stack holding the parameters , local variables and the return address. When a call finishes, its frame is popped and execution resumes in the caller, at the instruction after the call. Calls are therefore completed in last-in first-out order.
In Hanoi, Hanoi(3,A,B,C) pushes a frame, which calls Hanoi(2,A,C,B), which calls Hanoi(1,A,B,C); the deepest call returns first and its frame is popped, then the print of the caller executes, then the second recursive call is pushed. The maximum stack depth is , so the space used is . Recursion is thus a hidden use of the stack; the same algorithm can be written without recursion by managing an explicit stack.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
What is a circular queue? Explain with algorithm how insertion and deletion are performed in circular queue using array.
Answer
Circular queue
A circular queue is a queue in which the last position of the array is logically connected to the first position, so the array is treated as a ring. In a linear array queue, after rear reaches the last index no insertion is possible even if cells at the front were freed by deletions. In a circular queue the freed cells are reused, so memory is used efficiently.
Indices move with modulo arithmetic: , where is the array size.
Initially front = rear = -1.
- Empty:
front == -1. - Full:
(rear + 1) % N == front.
Insertion (enqueue)
Enqueue(Q, N, x)
if (rear + 1) % N == front
print "Queue overflow"; return
if front == -1
front = 0; rear = 0
else
rear = (rear + 1) % N
Q[rear] = x
Deletion (dequeue)
Dequeue(Q, N)
if front == -1
print "Queue underflow"; return
x = Q[front]
if front == rear // only one element
front = -1; rear = -1
else
front = (front + 1) % N
return x
Example with : insert 10, 20, 30, 40, 50 gives front = 0, rear = 4, the queue is full. Delete twice (10, 20 removed): front = 2. Insert 60: rear = , so 60 is stored at index 0 and the queue holds 30, 40, 50, 60.
Both operations take time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
What is the main difference between a stack and a queue? Write an algorithm to implement a stack using a linked list.
Answer
Difference between stack and queue
| Stack | Queue |
|---|---|
| LIFO: last element inserted is removed first | FIFO: first element inserted is removed first |
| Insertion (push) and deletion (pop) at the same end, the top | Insertion (enqueue) at the rear, deletion (dequeue) at the front |
| One pointer: top | Two pointers: front and rear |
| Used in recursion, expression evaluation, undo, parenthesis matching | Used in scheduling, buffering, BFS, printer spooling |
Stack using a linked list
Each node holds data and a next pointer. top points to the first node; push and pop both act on the head, so each takes time.
struct Node { int data; struct Node *next; };
Node *top = NULL;
Push(x)
new = allocate Node
if new == NULL: print "Overflow"; return
new->data = x
new->next = top
top = new
Pop()
if top == NULL: print "Underflow"; return
temp = top
x = temp->data
top = top->next
free(temp)
return x
C implementation of the two operations:
void push(int x) {
struct Node *n = (struct Node *)malloc(sizeof(struct Node));
if (n == NULL) { printf("Overflow\n"); return; }
n->data = x; n->next = top; top = n;
}
int pop() {
if (top == NULL) { printf("Underflow\n"); return -1; }
struct Node *t = top; int x = t->data;
top = top->next; free(t);
return x;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
Define singly LinkedList. Write a function in C or Java to delete a node at the beginning and at the end of singly linked list.
Answer
Singly linked list
A singly linked list is a linear collection of nodes where each node contains a data field and a pointer to the next node; the last node's pointer is NULL. A pointer head holds the address of the first node. Nodes are allocated dynamically, so the list grows and shrinks at run time, and insertion/deletion needs no shifting of elements.
struct Node { int data; struct Node *next; };
Delete at the beginning
struct Node* deleteBegin(struct Node *head) {
if (head == NULL) { // empty list
printf("List is empty\n");
return NULL;
}
struct Node *temp = head;
head = head->next; // second node becomes first
free(temp);
return head;
}
Time: .
Delete at the end
struct Node* deleteEnd(struct Node *head) {
if (head == NULL) {
printf("List is empty\n");
return NULL;
}
if (head->next == NULL) { // only one node
free(head);
return NULL;
}
struct Node *prev = head, *cur = head->next;
while (cur->next != NULL) { // go to the last node
prev = cur;
cur = cur->next;
}
prev->next = NULL; // second last becomes last
free(cur);
return head;
}
Time: , because the list must be traversed to reach the second last node.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Perform Inorder, and Postorder traversals for the given binary tree. (Tree given in the paper: root P with children Q and R; Q has children S and T; T has right child V; R has right child U.)
Answer
The tree: root P; P has children Q (left) and R (right); Q has children S (left) and T (right); T has a right child V; R has a right child U.
Inorder traversal (Left, Root, Right)
- Left subtree of P (rooted at Q): inorder(S) = S, then Q, then inorder(T) = T, V (T has no left child), giving S Q T V.
- Root: P.
- Right subtree of P (rooted at R): R has no left child, so R, then U, giving R U.
Postorder traversal (Left, Right, Root)
- Left subtree (rooted at Q): S, then postorder(T) = V, T, then Q, giving S V T Q.
- Right subtree (rooted at R): U, then R, giving U R.
- Root: P.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
Define "height" and "depth" in tree? Construct an AVL tree for following data: 35, 33, 42, 10, 14, 19, 27, 44, 26.
Answer
Height and depth
- Depth of a node is the number of edges on the path from the root to that node. The root has depth 0.
- Height of a node is the number of edges on the longest path from that node down to a leaf. A leaf has height 0. The height of a tree is the height of its root.
AVL tree
An AVL tree is a binary search tree in which, for every node, the heights of the left and right subtrees differ by at most 1 (balance factor ). Imbalance is repaired by rotations (LL, RR, LR, RL).
Construction for 35, 33, 42, 10, 14, 19, 27, 44, 26
- Insert 35, 33, 42: 35 is root with children 33 and 42. Balanced.
- Insert 10: left child of 33. Balanced.
- Insert 14: right child of 10. Node 33 has balance factor 2 and the new node is in the right subtree of its left child (LR case). Rotate left at 10, then right at 33. Subtree becomes 14 with children 10 and 33. Tree: 35 (14 (10, 33), 42).
- Insert 19: path 35, 14, 33, left of 33. Node 35 is unbalanced (left height 3, right height 1) with the insertion in the right subtree of its left child (LR). Rotate left at 14, then right at 35. Tree: 33 (14 (10, 19), 35 (-, 42)).
- Insert 27: path 33, 14, 19, right of 19. All balance factors are within . Tree: 33 (14 (10, 19 (-, 27)), 35 (-, 42)).
- Insert 44: right child of 42. Node 35 has balance factor (RR case). Rotate left at 35. Subtree becomes 42 with children 35 and 44.
- Insert 26: path 33, 14, 19, 27, left of 27. Node 19 is unbalanced (right height 2, left 0), and the insertion is in the left subtree of its right child (RL). Rotate right at 27, then left at 19. Subtree becomes 26 with children 19 and 27.
Final AVL tree
33
/ \
14 42
/ \ / \
10 26 35 44
/ \
19 27
Check: inorder is 10, 14, 19, 26, 27, 33, 35, 42, 44 (sorted), and every node's balance factor is , 0 or 1. Height of the tree is 3.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Construct the Huffman Tree for the given message and determine the Huffman code for each character. Additionally, calculate the total number of bits required to represent the message using Huffman encoding.
Message: B C A A D D D C C A C A C A C
Answer
Frequencies of the message B C A A D D D C C A C A C A C (15 characters):
| Character | A | B | C | D |
|---|---|---|---|---|
| Frequency | 5 | 1 | 6 | 3 |
Building the Huffman tree (repeatedly merge the two smallest weights)
- Smallest are B(1) and D(3): merge into node N1 = 4.
- Remaining weights: N1(4), A(5), C(6). Merge N1(4) and A(5) into N2 = 9.
- Remaining: C(6), N2(9). Merge into root = 15.
(15)
0/ \1
C(6) (9)
0/ \1
(4) A(5)
0/ \1
B(1) D(3)
Labelling left edges 0 and right edges 1 (smaller weight on the left):
| Character | Frequency | Code | Length |
|---|---|---|---|
| C | 6 | 0 | 1 |
| A | 5 | 11 | 2 |
| B | 1 | 100 | 3 |
| D | 3 | 101 | 3 |
Total bits
Encoded message: C=0, A=11, B=100, D=101 gives the 28-bit string for B C A A D D D C C A C A C A C. A fixed-length code would need bits, so Huffman coding saves 2 bits here.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
Perform a quicksort algorithm on the following array of numbers: (68, 34, 21, 43, 7, 18, 8, 56, 28, 17).
Answer
Method: choose the first element as pivot. Move i right to the first element greater than the pivot and j left to the first element less than or equal to the pivot; swap them if . When the pointers cross, swap the pivot with the element at j. Then sort the left and right parts recursively.
Array: 68, 34, 21, 43, 7, 18, 8, 56, 28, 17
Pass 1 (pivot 68): no element is greater than 68, and j stops at once at 17. Swap pivot with 17:
17, 34, 21, 43, 7, 18, 8, 56, 28 | 68
Pass 2 on [17, 34, 21, 43, 7, 18, 8, 56, 28] (pivot 17):
i stops at 34, j stops at 8; swap: 17, 8, 21, 43, 7, 18, 34, 56, 28.
i stops at 21, j stops at 7; swap: 17, 8, 7, 43, 21, 18, 34, 56, 28.
i stops at 43, j stops at 7 (index before i), so they have crossed. Swap pivot with 7:
[7, 8] | 17 | [43, 21, 18, 34, 56, 28]
Pass 3 on [7, 8]: pivot 7, nothing smaller on the right, so 7 stays and [8] is single. Sorted: 7, 8.
Pass 4 on [43, 21, 18, 34, 56, 28] (pivot 43):
i stops at 56, j stops at 28; swap: 43, 21, 18, 34, 28, 56.
Pointers cross; swap pivot with 28:
[28, 21, 18, 34] | 43 | [56]
Pass 5 on [28, 21, 18, 34] (pivot 28): i stops at 34, j stops at 18, crossed. Swap pivot with 18:
[18, 21] | 28 | [34]
Pass 6 on [18, 21]: pivot 18 is already in place; [21] is single.
Sorted array:
Average time , worst case .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
Write an algorithm or program for insertion sort with an example. And also write its time complexity.
Answer
Insertion sort
The array is divided into a sorted part (initially the first element) and an unsorted part. Each element (the key) of the unsorted part is taken in turn and inserted into its correct position in the sorted part by shifting larger elements one place right.
Algorithm
InsertionSort(A, n)
for i = 1 to n-1
key = A[i]
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j = j - 1
A[j+1] = key
Program in C
#include <stdio.h>
void insertionSort(int a[], int n) {
for (int i = 1; i < n; i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
int main() {
int a[] = {5, 2, 4, 6, 1, 3}, n = 6;
insertionSort(a, n);
for (int i = 0; i < n; i++) printf("%d ", a[i]);
return 0;
}
Example: 5, 2, 4, 6, 1, 3
| Pass | Key | Array after pass |
|---|---|---|
| 1 | 2 | 2, 5, 4, 6, 1, 3 |
| 2 | 4 | 2, 4, 5, 6, 1, 3 |
| 3 | 6 | 2, 4, 5, 6, 1, 3 |
| 4 | 1 | 1, 2, 4, 5, 6, 3 |
| 5 | 3 | 1, 2, 3, 4, 5, 6 |
Time complexity
- Best case (already sorted): one comparison per element, .
- Worst case (reverse sorted): the key is compared with and shifted past all earlier elements, , so .
- Average case: about half of the worst case, .
- Space: extra (in place). The sort is stable.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
What is perfect hashing? Explain linear probing and Separate chaining, providing suitable examples.
Answer
Hashing
Hashing stores a record with key at index of a table, e.g. , giving average search. When two keys map to the same index a collision occurs and must be resolved.
Perfect hashing
A perfect hash function maps a given static set of keys to distinct slots with no collisions, so a search takes worst case . If the table has exactly as many slots as keys it is a minimal perfect hash function. A common construction (FKS, two-level hashing) hashes keys into buckets with a first hash function; each bucket with keys gets its own secondary table of size and a secondary hash function chosen so that it has no collisions. Total space is . It suits fixed key sets such as reserved words of a compiler.
Linear probing (open addressing)
On collision, probe the next slots one by one: , until an empty slot is found.
Example: , , keys 23, 43, 13, 27, 33.
- 23 goes to slot 3.
- 43: slot 3 full, slot 4 is free, so 43 goes to 4.
- 13: slots 3, 4 full, so 13 goes to 5.
- 27 goes to 7.
- 33: slots 3, 4, 5 full, so 33 goes to 6.
| Slot | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|
| Key | 23 | 43 | 13 | 33 | 27 |
Drawback: primary clustering (long runs of filled slots lengthen searches).
Separate chaining
Each slot holds a linked list of all keys hashing to it. A colliding key is simply added to the list; the table never overflows.
Same keys, :
- Slot 3: 23 -> 43 -> 13 -> 33
- Slot 7: 27
Search cost is where is the load factor. It needs extra memory for pointers, but deletion is easy and performance degrades gracefully.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
Define Shortest path. Find shortest path algorithm Using Dijkstra's algorithm for the following graph starting point A and destination F. (Graph given in the paper with vertices A to F and edge weights.)
Answer
Shortest path
The shortest path between two vertices of a weighted graph is the path whose total edge weight is minimum among all paths joining them.
Dijkstra's algorithm (single source, non-negative weights)
Dijkstra(G, s)
for each vertex v: dist[v] = infinity; parent[v] = none; visited[v] = false
dist[s] = 0
repeat n times
u = unvisited vertex with smallest dist[u]
visited[u] = true
for each neighbour v of u
if dist[u] + w(u,v) < dist[v]
dist[v] = dist[u] + w(u,v)
parent[v] = u
Worked example
Take the graph with edges A-B = 4, A-C = 2, B-C = 1, B-D = 5, C-D = 8, C-E = 10, D-E = 2, D-F = 6, E-F = 3. Source A, destination F.
| Step | Selected | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|
| Init | 0 | inf | inf | inf | inf | inf | |
| 1 | A (0) | 0 | 4 | 2 | inf | inf | inf |
| 2 | C (2) | 0 | 3 | 2 | 10 | 12 | inf |
| 3 | B (3) | 0 | 3 | 2 | 8 | 12 | inf |
| 4 | D (8) | 0 | 3 | 2 | 8 | 10 | 14 |
| 5 | E (10) | 0 | 3 | 2 | 8 | 10 | 13 |
| 6 | F (13) | 0 | 3 | 2 | 8 | 10 | 13 |
Details: in step 2, B becomes , D becomes , E becomes . In step 3, D becomes . In step 4, E becomes and F becomes . In step 5, F becomes .
Following parents back from F: F <- E <- D <- B <- C <- A.
Shortest path: A -> C -> B -> D -> E -> F with total cost .
Time complexity with an array, with a binary heap.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 5 marks
Write short notes on: Priority Queue
Answer
Priority queue
A priority queue is an abstract data type in which every element has a priority, and the element with the highest priority (or lowest, in a min-priority queue) is removed first, regardless of the order of arrival. Elements of equal priority are served in FIFO order.
Operations
insert(x, p): add element with priority .deleteMax()/deleteMin(): remove and return the highest (lowest) priority element.peek(): look at the top element without removing it.
Implementations
| Implementation | Insert | Delete highest |
|---|---|---|
| Unsorted array / list | ||
| Sorted array / list | ||
| Binary heap |
The heap is the usual efficient implementation.
Types: ascending priority queue (smallest first) and descending priority queue (largest first).
Applications: CPU and job scheduling, Dijkstra's and Prim's algorithms, Huffman coding, event simulation, interrupt handling.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 5 marks
Write short notes on: Abstract Data Type (ADT)
Answer
Abstract Data Type (ADT)
An abstract data type is a mathematical model of a data structure that specifies the data it stores and the operations on that data, together with their behaviour, but hides how they are implemented. The user sees only the interface; the representation and algorithms are hidden (information hiding and encapsulation).
Example: Stack ADT
- Data: an ordered collection of elements accessed at one end (top).
- Operations:
push(x),pop(),peek(),isEmpty(),isFull(). - Behaviour: last in, first out.
The same stack ADT may be implemented with an array or a linked list; programs using it need not change.
Advantages
- Separates specification from implementation, so the implementation can change without affecting users.
- Improves modularity, reusability and maintainability.
- Reduces complexity by letting programmers think at the level of operations.
Other common ADTs: queue, list, priority queue, dictionary (map), set, tree and graph.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
What is data structure? Explain the types of data structure with examples.
Answer
Data structure
A data structure is a particular way of organising, storing and managing data in a computer so that it can be accessed and modified efficiently. Examples are arrays, stacks, queues, linked lists, trees and graphs.
Types of data structure
1. Primitive data structures: basic types supported directly by the machine/language, such as int, float, char, boolean, pointers.
2. Non-primitive data structures: built from primitive types. They are divided into:
(a) Linear data structures: elements are arranged sequentially, each element has a unique predecessor and successor (except the ends).
- Array: fixed-size collection of same-type elements in contiguous memory, accessed by index. Example:
int a[5]. - Linked list: nodes connected by pointers; singly, doubly or circular. Example: a playlist.
- Stack: LIFO. Example: undo operation, function calls.
- Queue: FIFO. Example: print queue, ticket counter.
(b) Non-linear data structures: elements are not in a sequence; one element can be linked to many.
- Tree: hierarchical, with a root and subtrees. Example: file system, binary search tree.
- Graph: set of vertices connected by edges. Example: road map, social network.
Other classification
- Static (fixed size, e.g. array) versus dynamic (size changes at run time, e.g. linked list).
- Homogeneous (same type, e.g. array) versus heterogeneous (different types, e.g. structure/record).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
What do mean by algorithm analysis? Suppose the given algorithm and compute its total time T(n) for worst case and average case.
Algorithm Cost
for i = 1 to n C1
for j = 1 to n-1 C2
printf("Pokhara University") C3
Algorithm Cost
for i = 1 to n C1
for j = 1 to n-1 C2
printf("Pokhara University") C3
Answer
Algorithm analysis
Algorithm analysis is the process of determining the resources an algorithm needs, mainly running time (time complexity) and memory (space complexity), as a function of the input size . It lets us compare algorithms independently of hardware and programming language, and choose the most efficient one.
Computing
- Outer loop
for i = 1 to n: the loop test is executed times, cost . - Inner loop
for j = 1 to n-1: for each of the values of , the test is executed times, total . printf: executed times for each , total .
Worst case and average case
The number of operations depends only on and not on the values of the input, so the best, average and worst cases are identical:
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
What do you mean by complexity of algorithms? Why do we need asymptotic notation? Describe about Big oh notation with example.
Answer
Complexity of algorithms
Complexity measures the resources an algorithm uses as a function of input size .
- Time complexity: the number of basic operations (steps) executed.
- Space complexity: the amount of memory needed (input plus auxiliary space).
It is studied for the best, average and worst cases; the worst case is most often quoted because it guarantees an upper limit.
Need for asymptotic notation
- Exact running time depends on the machine, compiler and language, so it is not a fair basis for comparison.
- Exact step counts are messy; for large only the fastest-growing term matters (for the term dominates).
- Asymptotic notations (, , ) describe the growth rate of the running time for large , ignoring constants and lower-order terms, giving a simple machine-independent way to compare algorithms.
Big-Oh notation
if there exist positive constants and such that
It gives an asymptotic upper bound on growth (worst-case bound).
Example: show .
For : . So with and , , hence .
Similarly for , so it is . Common orders: .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
What is a stack? How is it used in recursion? Explain with the example of determining the factorial of a number.
Answer
Stack
A stack is a linear data structure in which insertion (push) and deletion (pop) take place only at one end, called the top. It follows the Last In First Out (LIFO) rule. Other operations are peek, isEmpty and isFull.
Use of stack in recursion
When a function calls itself, the system keeps a call stack. Each call pushes an activation record (stack frame) containing the parameters, local variables and return address. When a call finishes, its frame is popped and control returns to the caller, which continues with the value returned. Calls are therefore completed in reverse order of their start, which is exactly LIFO.
Factorial example
int fact(int n) {
if (n == 0) return 1; // base case
return n * fact(n - 1); // recursive case
}
Trace of fact(4):
Winding (calls pushed): fact(4) -> fact(3) -> fact(2) -> fact(1) -> fact(0). The stack holds five frames, with fact(0) on top.
Unwinding (frames popped):
- fact(0) returns 1
- fact(1) returns
- fact(2) returns
- fact(3) returns
- fact(4) returns
So . The stack depth is , so the space is and the time is . Without the base case the stack would grow without limit and cause stack overflow.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
Define priority queue. Explain the implementation of circular queue with example.
Answer
Priority queue
A priority queue is a queue in which each element has a priority and the element with the highest priority is served (removed) first, irrespective of arrival order; elements with equal priority are served in the order of arrival. It is commonly implemented with a heap, giving insertion and deletion. It is used in CPU scheduling, Dijkstra's algorithm and Huffman coding.
Circular queue
A circular queue treats the array of size as a ring: after the last index the next position is index 0. This reuses the space freed by deletions, which a simple linear queue cannot. Indices advance as . Initially front = rear = -1; the queue is empty when front == -1 and full when (rear+1) % N == front.
Implementation
#define N 5
int q[N], front = -1, rear = -1;
void enqueue(int x) {
if ((rear + 1) % N == front) { printf("Overflow\n"); return; }
if (front == -1) front = rear = 0;
else rear = (rear + 1) % N;
q[rear] = x;
}
int dequeue() {
if (front == -1) { printf("Underflow\n"); return -1; }
int x = q[front];
if (front == rear) front = rear = -1;
else front = (front + 1) % N;
return x;
}
Example ()
- Enqueue 10, 20, 30, 40, 50: front = 0, rear = 4, queue full.
- Dequeue twice (10 and 20 leave): front = 2.
- Enqueue 60: rear = , so 60 is placed at index 0.
- Contents from front to rear: 30, 40, 50, 60.
Both operations take time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
Define Doubly Linked-list. Write a complete function in C or Java to insert a node at the beginning of singly linked list.
Answer
Doubly linked list
A doubly linked list is a linked list in which each node has three fields: a pointer to the previous node (prev), the data, and a pointer to the next node (next). The prev of the first node and the next of the last node are NULL. It can be traversed in both directions and a node can be deleted given only its own address, at the cost of an extra pointer per node.
struct Node {
int data;
struct Node *prev, *next;
};
Insert a node at the beginning
struct Node* insertBegin(struct Node *head, int x) {
struct Node *n = (struct Node *)malloc(sizeof(struct Node));
if (n == NULL) { printf("Memory not available\n"); return head; }
n->data = x;
n->prev = NULL;
n->next = head;
if (head != NULL)
head->prev = n; // old first node points back to the new node
head = n; // new node becomes the first node
return head;
}
Time complexity .
For a singly linked list (nodes with only data and next), insertion at the beginning is:
struct SNode* insertBeginS(struct SNode *head, int x) {
struct SNode *n = (struct SNode *)malloc(sizeof(struct SNode));
n->data = x;
n->next = head;
return n; // new node is the new head
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
What is the advantage of a linked stack? Write an algorithm to implement a stack using a linked list.
Answer
Advantages of a linked stack
- Dynamic size: it grows and shrinks at run time; no maximum size has to be fixed, so there is no stack overflow until memory itself is exhausted.
- Efficient memory use: memory is allocated only for elements actually stored, with no wasted unused array cells.
- Constant time operations: push and pop work at the head, , and no shifting is needed.
- No costly resizing/copying as with a full array.
The cost is an extra pointer per node and slower allocation.
Algorithm: stack using a linked list
Each node has data and next. top points to the first node and is NULL when the stack is empty.
Push(x)
new = allocate Node
if new == NULL: print "Overflow"; return
new->data = x
new->next = top
top = new
Pop()
if top == NULL: print "Underflow"; return
temp = top
x = temp->data
top = top->next
free(temp)
return x
Peek()
if top == NULL: print "Stack empty"
else return top->data
C code:
struct Node { int data; struct Node *next; } *top = NULL;
void push(int x) {
struct Node *n = (struct Node *)malloc(sizeof(struct Node));
if (n == NULL) { printf("Overflow\n"); return; }
n->data = x; n->next = top; top = n;
}
int pop() {
if (top == NULL) { printf("Underflow\n"); return -1; }
struct Node *t = top; int x = t->data;
top = top->next; free(t);
return x;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
Write an algorithm to implement a binary search tree (BST). What is the time complexity to search in the BST?
Answer
Binary search tree (BST)
A BST is a binary tree in which, for every node, all keys in the left subtree are smaller than the node's key and all keys in the right subtree are larger. An inorder traversal gives the keys in sorted order.
struct Node { int key; struct Node *left, *right; };
struct Node* newNode(int k) {
struct Node *n = (struct Node *)malloc(sizeof(struct Node));
n->key = k; n->left = n->right = NULL;
return n;
}
Insertion
struct Node* insert(struct Node *root, int k) {
if (root == NULL) return newNode(k);
if (k < root->key) root->left = insert(root->left, k);
else if (k > root->key) root->right = insert(root->right, k);
return root; // duplicates ignored
}
Search
struct Node* search(struct Node *root, int k) {
if (root == NULL || root->key == k) return root;
if (k < root->key) return search(root->left, k);
return search(root->right, k);
}
Inorder traversal
void inorder(struct Node *r) {
if (r != NULL) { inorder(r->left); printf("%d ", r->key); inorder(r->right); }
}
Algorithm for search
- Start at the root.
- If the tree is empty, the key is not found.
- If key equals the node's key, return the node.
- If key is smaller, continue in the left subtree; otherwise in the right subtree.
Time complexity of search
Each comparison moves down one level, so the time is where is the height of the tree.
- Best/average case (balanced tree, ): .
- Worst case (skewed tree, e.g. keys inserted in sorted order, ): .
Self-balancing trees such as AVL trees guarantee .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
How do you construct a Huffman tree? Explain with an example.
Answer
Huffman tree
Huffman coding is a lossless compression method that gives shorter binary codes to more frequent characters and longer codes to rarer ones, producing a prefix code (no code is a prefix of another). The code is derived from a Huffman tree.
Construction steps
- Count the frequency of each character and create a leaf node for each.
- Put all nodes in a priority queue (min-heap) ordered by frequency.
- Remove the two nodes with the smallest frequencies and create a new internal node whose frequency is their sum, with these two as children.
- Insert the new node back into the queue.
- Repeat steps 3 and 4 until one node (the root) remains.
- Label left edges 0 and right edges 1; the path from the root to a leaf gives the code of that character.
Example: A = 5, B = 9, C = 12, D = 13, E = 16, F = 45 (total 100).
- Merge A(5) + B(9) = 14.
- Merge C(12) + D(13) = 25.
- Merge 14 + E(16) = 30.
- Merge 25 + 30 = 55.
- Merge F(45) + 55 = 100 (root).
(100)
0/ \1
F(45) (55)
0/ \1
(25) (30)
0/ \1 0/ \1
C(12) D(13) (14) E(16)
0/ \1
A(5) B(9)
| Char | Frequency | Code |
|---|---|---|
| F | 45 | 0 |
| C | 12 | 100 |
| D | 13 | 101 |
| A | 5 | 1100 |
| B | 9 | 1101 |
| E | 16 | 111 |
Total bits bits, against bits for fixed 3-bit codes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
Why do you need to balance the binary tree? Construct an AVL tree for following data:
25, 46, 54, 58, 55, 34, 21, 39, 35, 10, 15
Answer
Why balance a binary tree
In an ordinary BST the shape depends on insertion order. Sorted input gives a skewed tree (like a linked list) of height , so search, insertion and deletion degrade to . Balancing keeps the height , so all these operations stay in the worst case. An AVL tree does this by keeping the balance factor (height of left - height of right) of every node in , using rotations after insertions and deletions.
Constructing the AVL tree
Data: 25, 46, 54, 58, 55, 34, 21, 39, 35, 10, 15
- Insert 25, 46, 54: 25 becomes unbalanced (right-right). Left rotation gives 46 (25, 54).
- Insert 58: right of 54.
- Insert 55: left of 58. Node 54 is unbalanced (right-left). Double rotation gives 55 (54, 58). Tree: 46 (25, 55 (54, 58)).
- Insert 34: right of 25. Insert 21: left of 25. Balanced.
- Insert 39: right of 34. Balanced.
- Insert 35: left of 39. Node 34 is unbalanced (right-left). Double rotation gives 35 (34, 39). Now 25 (21, 35 (34, 39)).
- Insert 10: left of 21. Balanced.
- Insert 15: right of 10. Node 21 is unbalanced (left-right). Double rotation gives 15 (10, 21).
Final AVL tree
46
/ \
25 55
/ \ / \
15 35 54 58
/ \ / \
10 21 34 39
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
Write an algorithm/function to sort the below array using selection sort: 12, 8, 9, 3, 11, 5, 4
Answer
Idea: in each pass find the smallest element of the unsorted part and swap it with the first element of that part.
Algorithm
SelectionSort(A, n)
for i = 0 to n-2
min = i
for j = i+1 to n-1
if A[j] < A[min]
min = j
swap A[i], A[min]
C function
void selectionSort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
int t = a[i]; a[i] = a[min]; a[min] = t;
}
}
Trace for 12, 8, 9, 3, 11, 5, 4:
| Pass | Minimum | Array after pass |
|---|---|---|
| 1 | 3 | 3, 8, 9, 12, 11, 5, 4 |
| 2 | 4 | 3, 4, 9, 12, 11, 5, 8 |
| 3 | 5 | 3, 4, 5, 12, 11, 9, 8 |
| 4 | 8 | 3, 4, 5, 8, 11, 9, 12 |
| 5 | 9 | 3, 4, 5, 8, 9, 11, 12 |
| 6 | 11 | 3, 4, 5, 8, 9, 11, 12 |
Sorted array: 3, 4, 5, 8, 9, 11, 12. Time complexity is in all cases, with extra space.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
Define external and internal sorting. Perform a quicksort algorithm on the following array of numbers: 68, 34, 21, 43, 7, 18, 8, 56, 28, 17
Answer
Internal sorting sorts data that fits entirely in main memory (RAM), for example quicksort, heap sort, insertion sort.
External sorting sorts data too large for main memory, so it is kept on external storage (disk/tape) and processed in chunks; typically the data is split into sorted runs that fit in memory, which are then merged (external merge sort). The cost is dominated by disk I/O.
Quicksort of 68, 34, 21, 43, 7, 18, 8, 56, 28, 17
The first element is the pivot; moves right to find an element greater than the pivot, moves left to find an element not greater than it. If swap them; otherwise swap the pivot with .
Pass 1 (pivot 68): no element exceeds 68; stops at 17. Swap 68 and 17:
17, 34, 21, 43, 7, 18, 8, 56, 28, 68
Pass 2 (pivot 17):
- at 34, at 8: swap gives 17, 8, 21, 43, 7, 18, 34, 56, 28
- at 21, at 7: swap gives 17, 8, 7, 43, 21, 18, 34, 56, 28
- at 43, at 7 (): swap pivot with 7 gives 7, 8, 17, 43, 21, 18, 34, 56, 28
Left part (7, 8) is already sorted.
Right part (43, 21, 18, 34, 56, 28), pivot 43:
- at 56, at 28: swap gives 43, 21, 18, 34, 28, 56
- : swap pivot with 28 gives 28, 21, 18, 34, 43, 56
(28, 21, 18, 34) with pivot 28 becomes 18, 21, 28, 34; (18, 21) is already in order.
Sorted array: 7, 8, 17, 18, 21, 28, 34, 43, 56, 68
Average time , worst case .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
Given input {1, 16, 49, 36, 25, 64, 0, 81, 4, 9} and a hash function . Show the resulting:
i. hash table using linear probing
ii. hash table using separate chaining
Answer
Keys: 1, 16, 49, 36, 25, 64, 0, 81, 4, 9 with , table size 10.
| Key | h(x) |
|---|---|
| 1 | 1 |
| 16 | 6 |
| 49 | 9 |
| 36 | 6 (collision) |
| 25 | 5 |
| 64 | 4 |
| 0 | 0 |
| 81 | 1 (collision) |
| 4 | 4 (collision) |
| 9 | 9 (collision) |
i. Linear probing (try the next slot, wrapping around, until empty)
- 1 goes to 1; 16 to 6; 49 to 9.
- 36: slot 6 full, goes to 7.
- 25 to 5; 64 to 4; 0 to 0.
- 81: slot 1 full, goes to 2.
- 4: slots 4, 5, 6, 7 full, goes to 8.
- 9: slot 9 full, then 0, 1, 2 full, goes to 3.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Key | 0 | 1 | 81 | 9 | 64 | 25 | 16 | 36 | 4 | 49 |
ii. Separate chaining (each slot holds a list, new keys appended)
| Index | Chain |
|---|---|
| 0 | 0 |
| 1 | 1 -> 81 |
| 2 | empty |
| 3 | empty |
| 4 | 64 -> 4 |
| 5 | 25 |
| 6 | 16 -> 36 |
| 7 | empty |
| 8 | empty |
| 9 | 49 -> 9 |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
What do you mean by spanning tree of graph? Find the minimal spanning tree of the following graph. (Weighted graph given in the paper with vertices a to f.)
Answer
Spanning tree
A spanning tree of a connected undirected graph with vertices is a subgraph that contains all the vertices, is connected, and has no cycles; it therefore has exactly edges. In a weighted graph, the minimum spanning tree (MST) is the spanning tree with the smallest total edge weight. It is found by Kruskal's or Prim's algorithm.
Kruskal's algorithm
- Sort all edges by increasing weight.
- Take edges in that order and add an edge if it does not form a cycle with the edges already chosen.
- Stop when edges have been chosen.
Worked example
Take the graph with edges a-b = 3, a-c = 5, b-c = 1, b-d = 6, c-d = 4, c-e = 7, d-e = 2, d-f = 8, e-f = 5. Here , so the MST has 5 edges.
Sorted: b-c 1, d-e 2, a-b 3, c-d 4, a-c 5, e-f 5, b-d 6, c-e 7, d-f 8.
| Edge | Weight | Decision |
|---|---|---|
| b-c | 1 | accept |
| d-e | 2 | accept |
| a-b | 3 | accept |
| c-d | 4 | accept (joins {a,b,c} and {d,e}) |
| a-c | 5 | reject (cycle a-b-c) |
| e-f | 5 | accept (adds f) |
Five edges are chosen, so we stop.
MST edges: b-c, d-e, a-b, c-d, e-f
Total weight .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 5 marks
Write short notes on: Binary Search
Answer
Binary search finds a key in a sorted array by repeatedly halving the search range. It compares the key with the middle element: if equal, it is found; if the key is smaller, search the left half; otherwise search the right half.
Algorithm
BinarySearch(A, n, key)
low = 0; high = n - 1
while low <= high
mid = (low + high) / 2
if A[mid] == key
return mid
else if key < A[mid]
high = mid - 1
else
low = mid + 1
return -1
Example: A = 10, 20, 30, 40, 50, 60, 70; key = 60.
- low = 0, high = 6, mid = 3, A[3] = 40 < 60, so low = 4.
- low = 4, high = 6, mid = 5, A[5] = 60, found at index 5.
Complexity: each step halves the range, so the time is (best case ) and the space is for the iterative version. It requires sorted data and random access, so it is not suitable for ordinary linked lists. Linear search takes .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
Define ADT. Explain why it is needed. Explain different types of data structure with examples.
Answer
ADT (Abstract Data Type)
An ADT is a mathematical model that defines a set of data values and the operations on them, without specifying how they are implemented. For example, the Stack ADT defines push, pop, peek and isEmpty, but not whether an array or a linked list stores the elements.
Why it is needed
- Separates the interface (what) from the implementation (how), giving abstraction and information hiding.
- The implementation can be changed without changing the programs that use it.
- Improves modularity, reusability, and ease of maintenance and testing.
- Lets programmers think at the problem level rather than the memory level.
Types of data structures
Data Structures
|-- Primitive: int, float, char, boolean
|-- Non-primitive
|-- Linear: array, linked list, stack, queue
|-- Non-linear: tree, graph
- Primitive: basic types provided by the language, such as
int,float,char. - Linear: elements are arranged in sequence.
- Array: fixed-size contiguous collection with index access, e.g. marks of 50 students.
- Linked list: nodes joined by pointers, with dynamic size, e.g. a playlist.
- Stack: LIFO, e.g. undo operation, function calls.
- Queue: FIFO, e.g. a printer queue.
- Non-linear: elements form a hierarchy or network.
- Tree: e.g. a folder structure, binary search tree.
- Graph: vertices and edges, e.g. a road network, social network.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
Write a complete program in C/C++ to demonstrate push and pop operation in a Stack using Linked list.
Answer
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
struct Node *top = NULL;
void push(int x) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Stack Overflow (memory full)\n");
return;
}
newNode->data = x;
newNode->next = top;
top = newNode;
printf("%d pushed\n", x);
}
void pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return;
}
struct Node *temp = top;
printf("%d popped\n", temp->data);
top = top->next;
free(temp);
}
void display() {
struct Node *p = top;
if (p == NULL) {
printf("Stack is empty\n");
return;
}
printf("Stack (top to bottom): ");
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int choice, x;
while (1) {
printf("\n1. Push 2. Pop 3. Display 4. Exit\nEnter choice: ");
if (scanf("%d", &choice) != 1) break;
switch (choice) {
case 1:
printf("Enter value: ");
scanf("%d", &x);
push(x);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}
Both push and pop work at the head of the list (top), so each takes time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
Why do you need an expression in postfix? Convert the following expression into postfix.
Answer
Need for postfix expressions
In infix form (A + B * C) the order of evaluation depends on operator precedence, associativity and parentheses, so a computer needs several scans to evaluate it. In postfix (Reverse Polish) form the operator comes after its operands, so:
- no parentheses and no precedence rules are needed,
- the expression is evaluated in a single left-to-right scan using one stack (push operands; on an operator, pop two operands, apply it, push the result),
- it is easy for compilers to generate code from.
Conversion of
Scan left to right using a stack for operators; ( is pushed and ) pops until (.
| Symbol | Stack | Output |
|---|---|---|
| ( | ( | |
| ( | ( ( | |
| A | ( ( | A |
| + | ( ( + | A |
| B | ( ( + | A B |
| ) | ( | A B + |
| - | ( - | A B + |
| C | ( - | A B + C |
| * | ( - * | A B + C |
| ( | ( - * ( | A B + C |
| D | ( - * ( | A B + C D |
| / | ( - * ( / | A B + C D |
| E | ( - * ( / | A B + C D E |
| ) | ( - * | A B + C D E / |
| ) | (empty) | A B + C D E / * - |
| + | + | A B + C D E / * - |
| F | + | A B + C D E / * - F |
| end | A B + C D E / * - F + |
Postfix:
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
How does an AVL tree solve the issues of Binary Search Tree? Construct an AVL Tree from the following Data: 22,27,31,10,5,16,29,19,11,3,4,8.
Answer
How AVL solves the problems of a BST
A plain BST can become skewed (for example when keys arrive in sorted order), giving height and search, insert and delete. An AVL tree is a self-balancing BST: for each node, the heights of the left and right subtrees differ by at most 1 (balance factor , , ). After an insertion or deletion that breaks this, single or double rotations (LL, RR, LR, RL) restore balance. The height always stays , so all operations are guaranteed in the worst case.
Construction: 22, 27, 31, 10, 5, 16, 29, 19, 11, 3, 4, 8
- Insert 22, 27, 31: 22 is unbalanced (RR). Left rotation gives 27 (22, 31).
- Insert 10: left of 22.
- Insert 5: left of 10. Node 22 is unbalanced (LL). Right rotation gives 10 (5, 22). Tree: 27 (10 (5, 22), 31).
- Insert 16: left of 22. Node 27 is unbalanced (LR). Double rotation gives 22 (10 (5, 16), 27 (-, 31)).
- Insert 29: left of 31. Node 27 is unbalanced (RL). Double rotation gives 29 (27, 31). Tree: 22 (10 (5, 16), 29 (27, 31)).
- Insert 19: right of 16. Insert 11: left of 16. Balanced.
- Insert 3: left of 5. Balanced.
- Insert 4: right of 3. Node 5 is unbalanced (LR). Double rotation gives 4 (3, 5).
- Insert 8: right of 5. Node 22 becomes unbalanced (LL): its left subtree (rooted at 10) has height 4 and its right subtree (rooted at 29) has height 2. Right rotation at 22 makes 10 the root, and 16 (11, 19) becomes the left subtree of 22.
Final AVL tree
10
/ \
4 22
/ \ / \
3 5 16 29
\ / \ / \
8 11 19 27 31
The tree has 4 levels and all balance factors are within .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
How do you traverse a Binary tree? Perform In-order, Pre-order and Post-order traversal of the given tree. (Tree given in the paper: root F with children B and G; B has children A and D; D has children C and E; G has right child I; I has left child H.)
Answer
Traversal of a binary tree
Traversal means visiting every node exactly once. The three depth-first recursive methods are:
- Inorder (LNR): traverse the left subtree, visit the root, traverse the right subtree.
- Preorder (NLR): visit the root, traverse the left subtree, traverse the right subtree.
- Postorder (LRN): traverse the left subtree, traverse the right subtree, visit the root.
(Level-order traversal uses a queue and visits level by level.)
The tree: root F; F has children B and G; B has children A and D; D has children C and E; G has right child I; I has left child H.
Inorder (L, N, R)
- Left of F (rooted at B): A, B, then D's subtree (C, D, E): A B C D E
- Root F
- Right of F: G, then I's subtree (H, I): G H I
Preorder (N, L, R)
- F, then B's subtree: B, A, then D, C, E
- then G's subtree: G, I, H
Postorder (L, R, N)
- Left subtree of F: A, then D's subtree (C, E, D), then B: A C E D B
- Right subtree of F: H, I, G
- Root: F
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
What is a collision in hashing? Describe any three techniques to resolve the collision.
Answer
Collision
In hashing, a key is mapped to a table index by a hash function . A collision occurs when two different keys hash to the same index, . Since the key space is larger than the table, collisions cannot be avoided entirely and must be resolved.
Techniques to resolve collisions
1. Separate chaining. Each slot holds a linked list of all keys that hash to it; a colliding key is added to the list. With , and keys 12, 22, 32, index 2 holds 12 -> 22 -> 32. It is simple, never fills up and deletion is easy, but needs extra memory for pointers. Average search time is , with load factor .
2. Linear probing (open addressing). If slot is taken, try for until a free slot is found. With the same keys, 12 goes to 2, 22 to 3 and 32 to 4. It is simple and cache friendly, but suffers from primary clustering (long runs of filled slots).
3. Quadratic probing. The probe sequence is , so the probes jump 1, 4, 9, ... slots. For 12, 22, 32: 12 goes to 2, 22 to 3 (), 32 to 6 (). This reduces primary clustering, though keys with the same hash follow the same probe path (secondary clustering).
4. Double hashing. The step comes from a second hash: , e.g. . Different keys follow different probe sequences, which avoids both kinds of clustering, at the cost of computing two hashes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
Define Priority queue. Create a Min heap from the given data and also perform deletion of root node: 4, 6, 52, 17, 28, 39, 43, 11.
Answer
Priority queue. A priority queue is an abstract data type in which every element carries a priority and the element with the highest priority (for a min priority queue, the smallest key) is removed first, regardless of the order of arrival. Its main operations are insert(x), findMin() and deleteMin(). It is usually implemented with a binary heap, which gives insertion and deletion.
Min heap. A min heap is a complete binary tree in which every parent is smaller than or equal to its children. It is stored in an array: the children of index are at and .
Building the heap by inserting 4, 6, 52, 17, 28, 39, 43, 11 one at a time (insert at the next free leaf, then percolate up):
| Insert | Heap array after insertion |
|---|---|
| 4 | [4] |
| 6 | [4, 6] |
| 52 | [4, 6, 52] |
| 17 | [4, 6, 52, 17] |
| 28 | [4, 6, 52, 17, 28] |
| 39 | placed under 52, 39 < 52, swap: [4, 6, 39, 17, 28, 52] |
| 43 | placed under 39, no swap: [4, 6, 39, 17, 28, 52, 43] |
| 11 | placed under 17, 11 < 17 swap; 11 > 6 stop: [4, 6, 39, 11, 28, 52, 43, 17] |
Final min heap:
4
/ \
6 39
/ \ / \
11 28 52 43
/
17
Deleting the root (4).
- Remove 4 and move the last element 17 to the root: [17, 6, 39, 11, 28, 52, 43].
- Percolate down: the smaller child of 17 is 6, so swap: [6, 17, 39, 11, 28, 52, 43].
- The children of 17 are now 11 and 28; the smaller is 11 < 17, so swap: [6, 11, 39, 17, 28, 52, 43].
- 17 is now a leaf, so stop.
Heap after deletion:
6
/ \
11 39
/ \ / \
17 28 52 43
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
Define leftist heap. Write the steps used to perform merging process of two leftist heaps with proper example.
Answer
Leftist heap. A leftist heap is a binary tree that is heap-ordered (each parent is not larger than its children in a min leftist heap) and satisfies the leftist property: for every node, the null path length (npl) of its left child is at least the npl of its right child. The npl of a node is the length of the shortest path from the node to a node with no two children; npl(null) = -1 and npl(leaf) = 0. Consequently the right path is always short (at most nodes), and merging, insertion and deleteMin all take time.
Steps of merging two leftist heaps H1 and H2.
- If one heap is empty, return the other.
- Compare the roots. Let the heap with the smaller root be H1 (swap names if needed).
- Recursively merge the right subtree of H1 with H2, and make the result the new right child of H1.
- If the npl of the left child is smaller than the npl of the right child, swap the two children (restore the leftist property).
- Update npl(root) = npl(right child) + 1 and return the root.
Example. H1: root 3 with left child 10 and right child 8 (npl = 1). H2: root 6 with left child 12 and no right child (npl = 0).
- , so 3 stays the root and we merge right(3) = 8 with H2.
- Merge(8, H2): , so 6 is the root and we merge right(6) = null with 8, which gives 8. So 6 gets left child 12 and right child 8; both have npl 0, so npl(6) = 1.
- Back at 3: its right child is now the subtree rooted at 6 (npl 1) while its left child 10 has npl 0. Since npl(left) < npl(right), swap the children: left = 6, right = 10.
Result:
3
/ \
6 10
/ \
12 8
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
What is External Sorting? Explain the process of Quick sort with an example.
Answer
External sorting. External sorting is used when the data to be sorted is too large to fit in main memory and resides on disk or tape. The usual method is external merge sort: (1) read as much data as fits in memory, sort it with an internal sort and write it out as a sorted run; (2) repeatedly merge the runs (two-way or k-way merge) using input buffers and one output buffer until a single sorted file remains. The aim is to minimise the number of disk passes, because disk I/O dominates the cost.
Quick sort. Quick sort is a divide-and-conquer algorithm.
- Choose a pivot (here the first element).
- Partition: move elements smaller than the pivot to its left and larger ones to its right, so the pivot reaches its final position.
- Recursively sort the left and right parts.
Example: sort 45, 30, 80, 10, 60, 25, 70.
- Pivot = 45. Scan from the left for an element > 45 (80) and from the right for an element ≤ 45 (25). Swap them: 45, 30, 25, 10, 60, 80, 70. Continue: the left scan stops at 60, the right scan stops at 10; the pointers have crossed, so swap the pivot with 10: 10, 30, 25, 45, 60, 80, 70. 45 is in its final place.
- Left part (10, 30, 25): pivot 10 is already in place; the right part (30, 25) with pivot 30 becomes 25, 30. Left part sorted: 10, 25, 30.
- Right part (60, 80, 70): pivot 60 is in place; (80, 70) with pivot 80 becomes 70, 80. Right part sorted: 60, 70, 80.
Sorted array: 10, 25, 30, 45, 60, 70, 80.
Complexity: best and average case ; worst case (already sorted input with a bad pivot choice); space for recursion.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
What do you mean by minimum spanning tree? Find out the minimum spanning tree of the given graph using Prim's algorithm. (Weighted graph given in the paper.)
Answer
Minimum spanning tree (MST). For a connected, undirected, weighted graph with vertices, a spanning tree is a subgraph that connects all vertices using exactly edges and has no cycle. The minimum spanning tree is the spanning tree whose total edge weight is the smallest.
Prim's algorithm. Start from any vertex and repeatedly add the cheapest edge that joins a vertex in the tree to a vertex outside it, until all vertices are included.
Since the figure is not reproduced here, take the weighted graph on vertices A to F with edges: A-B = 4, A-C = 3, B-C = 1, B-D = 2, C-D = 4, D-E = 2, D-F = 7, E-F = 6.
Start at A.
| Step | Tree vertices | Candidate edges | Edge chosen |
|---|---|---|---|
| 1 | {A} | A-B 4, A-C 3 | A-C (3) |
| 2 | {A, C} | A-B 4, C-B 1, C-D 4 | C-B (1) |
| 3 | {A, B, C} | B-D 2, C-D 4 | B-D (2) |
| 4 | {A, B, C, D} | D-E 2, D-F 7 | D-E (2) |
| 5 | {A, B, C, D, E} | E-F 6, D-F 7 | E-F (6) |
MST edges: A-C, C-B, B-D, D-E, E-F (5 edges for 6 vertices).
Total weight = .
Complexity: with an adjacency matrix, with a binary heap.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
Define Dynamic Programming. Explain Divide and Conquer Algorithm with example.
Answer
Dynamic programming (DP). Dynamic programming is a technique for solving problems that have overlapping subproblems and optimal substructure. Each subproblem is solved only once and its result is stored in a table (memoization, top-down, or tabulation, bottom-up) and reused, instead of being recomputed. Examples are Fibonacci numbers, the 0/1 knapsack problem, longest common subsequence and matrix-chain multiplication.
Divide and Conquer. This strategy solves a problem in three steps.
- Divide the problem into smaller independent subproblems of the same type.
- Conquer each subproblem recursively; a small enough subproblem is solved directly (base case).
- Combine the sub-solutions to get the solution of the original problem.
Its running time is described by a recurrence such as .
Example: merge sort of 38, 27, 43, 3.
- Divide: [38, 27, 43, 3] into [38, 27] and [43, 3], then into single elements [38], [27], [43], [3].
- Conquer: single elements are already sorted.
- Combine: merge [38] and [27] into [27, 38]; merge [43] and [3] into [3, 43]; merge [27, 38] and [3, 43] into [3, 27, 38, 43].
Here , so . Other examples: binary search, quick sort, Strassen's matrix multiplication.
Difference from DP: in divide and conquer the subproblems are independent, whereas in dynamic programming they overlap and their results are stored for reuse.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 5 marks
Write short notes on: Extendable Hashing
Answer
Extendable hashing is a dynamic hashing technique for large files kept on disk. It allows the hash table to grow and shrink as records are inserted and deleted, without rehashing all the data.
- The hash function maps a key to a binary string, and only the first bits (the global depth) are used to index a directory of pointers.
- Each directory entry points to a bucket (a disk block) holding a limited number of records. Each bucket has a local depth , the number of bits that all its keys share; several directory entries may point to the same bucket.
- Insertion: go to the bucket given by the first bits. If it has room, store the key. If it is full and , split the bucket, increase its local depth and redistribute the keys using one more bit. If it is full and , double the directory ( increases by 1) and then split the bucket.
- Search needs at most one directory access and one bucket access.
Advantages: no overflow chains, only the full bucket is split, and lookups are fast. Disadvantage: the directory can become large if the keys are unevenly distributed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 5 marks
Write short notes on: Breadth First Search in Graph
Answer
Breadth First Search (BFS) is a graph traversal method that visits a start vertex, then all its neighbours, then all neighbours of those neighbours, level by level. It uses a queue (FIFO) and a visited array.
Algorithm
- Mark the start vertex visited and enqueue it.
- While the queue is not empty: dequeue a vertex and process it; for each unvisited neighbour of , mark it visited and enqueue it.
Example. Graph edges: A-B, A-C, B-D, C-D, D-E. Starting from A: queue [A]; visit A, enqueue B, C; visit B, enqueue D; visit C (D is already visited); visit D, enqueue E; visit E. BFS order: A, B, C, D, E.
Complexity: with an adjacency list, with an adjacency matrix.
Applications: shortest path in an unweighted graph, finding connected components, testing whether a graph is bipartite, and web crawling or social-network "friends at distance k".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
Why do we need data structure? Explain different types of linear and non-linear data structures.
Answer
Need for data structures. A data structure is a way of organising and storing data in memory so that it can be accessed and modified efficiently. We need data structures because:
- they let us organise large amounts of data logically (e.g. a stack for undo, a queue for printing jobs);
- the right structure makes searching, insertion, deletion and sorting fast, reducing time and memory use;
- they support abstraction and reuse, since the same structure can be used in many programs;
- they are the basis of efficient algorithms (compilers, databases, operating systems, networks).
Linear data structures. The elements form a sequence, each element having one predecessor and one successor, and are traversed in a single run.
- Array: fixed-size collection of same-type elements in contiguous memory with direct index access.
- Linked list: nodes holding data and a pointer to the next node (singly, doubly, circular); dynamic size, easy insertion and deletion.
- Stack: insertion and deletion at one end only (LIFO), with push and pop.
- Queue: insertion at the rear and deletion at the front (FIFO); variants are circular queue, deque and priority queue.
Non-linear data structures. The elements are not in a sequence; one element may be connected to several others.
- Tree: hierarchical structure with a root and child nodes (binary tree, BST, AVL, B-tree, heap). Used for file systems and expression parsing.
- Graph: a set of vertices connected by edges (directed or undirected, weighted or not). Used for road maps, networks and social networks.
- Hash table (often also listed here) maps keys to positions using a hash function for near constant-time lookup.
Linear structures are simple and easy to implement but memory is used sequentially; non-linear structures use memory more flexibly and model complex relationships.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 8 marks
Write a C/C++ function to perform the following operation in a singly linked list.
i. To insert a new node at the start of the list.
ii. To remove an end node from the list.
Answer
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
/* i. Insert a new node at the start of the list */
struct Node* insertAtStart(struct Node *head, int value) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
return head;
}
newNode->data = value;
newNode->next = head; /* new node points to the old first node */
head = newNode; /* head now points to the new node */
return head;
}
/* ii. Remove the end (last) node from the list */
struct Node* removeEnd(struct Node *head) {
if (head == NULL) { /* empty list */
printf("List is empty\n");
return NULL;
}
if (head->next == NULL) { /* only one node */
free(head);
return NULL;
}
struct Node *prev = head;
struct Node *curr = head->next;
while (curr->next != NULL) { /* move to the last node */
prev = curr;
curr = curr->next;
}
prev->next = NULL; /* second last becomes last */
free(curr);
return head;
}
void display(struct Node *head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
struct Node *head = NULL;
head = insertAtStart(head, 30);
head = insertAtStart(head, 20);
head = insertAtStart(head, 10);
display(head); /* 10 -> 20 -> 30 -> NULL */
head = removeEnd(head);
display(head); /* 10 -> 20 -> NULL */
return 0;
}
Insertion at the start takes time; removal of the last node takes time because the list must be traversed to find the second last node.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
Why queue is called FIFO structure? Implement the enqueue and dequeue operations of Queue using C/C++ code.
Answer
Why FIFO? A queue is called a FIFO (First In, First Out) structure because elements are inserted at one end (the rear) and removed from the other end (the front). The element that entered first is therefore the first to leave, like people waiting in a line at a ticket counter.
Implementation (array-based circular queue in C):
#include <stdio.h>
#define SIZE 5
int queue[SIZE];
int front = -1, rear = -1;
int isFull() { return (rear + 1) % SIZE == front; }
int isEmpty() { return front == -1; }
void enqueue(int x) {
if (isFull()) {
printf("Queue overflow\n");
return;
}
if (isEmpty())
front = 0;
rear = (rear + 1) % SIZE;
queue[rear] = x;
}
int dequeue() {
if (isEmpty()) {
printf("Queue underflow\n");
return -1;
}
int x = queue[front];
if (front == rear) /* last element removed */
front = rear = -1;
else
front = (front + 1) % SIZE;
return x;
}
int main() {
enqueue(10); enqueue(20); enqueue(30);
printf("%d\n", dequeue()); /* 10 */
printf("%d\n", dequeue()); /* 20 */
enqueue(40);
printf("%d\n", dequeue()); /* 30 */
return 0;
}
Both enqueue and dequeue run in time. The elements come out in the order 10, 20, 30, 40, the same order in which they were inserted.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
Define Binary search tree. Create an AVL Tree from the following data and show the deletion of the root. 10, 55, 55, 60, 70, 62, 20, 18, 12, 35.
Answer
Binary search tree (BST). A BST is a binary tree in which, for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger than the node's key. An AVL tree is a BST in which the balance factor (height of left subtree minus height of right subtree) of every node is -1, 0 or +1; imbalance is repaired by rotations.
Construction (the duplicate 55 is ignored because a BST/AVL tree holds distinct keys):
- Insert 10, then 55 (right of 10), then 60 (right of 55): node 10 has balance -2 (right-right case), so rotate left. Root becomes 55 with children 10 and 60.
- Insert 70 (right of 60). Balanced.
- Insert 62 (left of 70): node 60 is unbalanced (right-left case). Double rotation makes 62 the subtree root with children 60 and 70. Tree: 55 (10, 62(60, 70)).
- Insert 20 (right of 10). Balanced.
- Insert 18 (left of 20): node 10 is unbalanced (right-left case). Double rotation makes 18 the subtree root with children 10 and 20. Tree: 55 (18(10, 20), 62(60, 70)).
- Insert 12 (right of 10) and 35 (right of 20). All balance factors stay within ±1.
Final AVL tree:
55
/ \
18 62
/ \ / \
10 20 60 70
\ \
12 35
Deleting the root (55). The root has two children, so replace it by its inorder successor, the smallest key in the right subtree, which is 60. Delete 60 from its old position (it is a leaf) and put its value at the root.
60
/ \
18 62
/ \ \
10 20 70
\ \
12 35
Check balance: node 62 has balance -1, node 60 has left height 3 and right height 2 (balance +1), so every node is still within ±1 and no rotation is needed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 8 marks
What are the different tree traversal algorithms? Explain each with an example.
Answer
Tree traversal means visiting every node of a tree exactly once. For a binary tree the depth-first traversals are inorder, preorder and postorder, and there is also the breadth-first level order traversal.
Consider the tree:
A
/ \
B C
/ \ \
D E F
1. Inorder (Left, Root, Right).
inorder(node): if node != NULL
inorder(node->left); visit(node); inorder(node->right)
Result: D B E A C F. For a BST this gives the keys in sorted order.
2. Preorder (Root, Left, Right).
preorder(node): if node != NULL
visit(node); preorder(node->left); preorder(node->right)
Result: A B D E C F. Used to copy a tree and to get prefix expressions.
3. Postorder (Left, Right, Root).
postorder(node): if node != NULL
postorder(node->left); postorder(node->right); visit(node)
Result: D E B F C A. Used to delete a tree and to get postfix expressions.
4. Level order (breadth first). Visit nodes level by level from left to right using a queue: enqueue the root; repeatedly dequeue a node, visit it and enqueue its children. Result: A B C D E F.
Each traversal visits every node once, so the time complexity is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 10 marks
Define Hash Table and Load factor. Construct a hash table T of size 11 and Insert the keys of array S = {5, 40, 18, 22, 16, 30, 27} with the hash function: using:
i) Separate Chaining
ii) Quadratic Probing
Answer
Hash table. A hash table is a data structure that stores keys in an array of size and uses a hash function to compute the index where key is stored, giving average search, insertion and deletion.
Load factor. , where is the number of keys stored and is the table size. It measures how full the table is; a larger means more collisions. Here .
Hash values with : 5 → 5, 40 → 7, 18 → 7, 22 → 0, 16 → 5, 30 → 8, 27 → 5.
i) Separate chaining (each slot holds a linked list of the keys that hash to it):
| Index | Chain |
|---|---|
| 0 | 22 |
| 1-4 | empty |
| 5 | 5 → 16 → 27 |
| 6 | empty |
| 7 | 40 → 18 |
| 8 | 30 |
| 9-10 | empty |
ii) Quadratic probing, using index for :
- 5 → slot 5.
- 40 → slot 7.
- 18 → slot 7 is full; : slot 8, free, so 18 goes to 8.
- 22 → slot 0.
- 16 → slot 5 is full; : slot 6, free, so 16 goes to 6.
- 30 → slot 8 is full; : slot 9, free, so 30 goes to 9.
- 27 → slot 5 full; : slot 6 full; : full; : , free, so 27 goes to 3.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Key | 22 | 27 | 5 | 16 | 40 | 18 | 30 |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 5 marks
Explain binary search algorithm with an example.
Answer
Binary search finds a key in a sorted array by repeatedly halving the search range. Compare the key with the middle element: if equal, the search ends; if the key is smaller, continue in the left half; otherwise continue in the right half.
Algorithm
low = 0, high = n - 1
while low <= high:
mid = (low + high) / 2
if a[mid] == key: return mid
else if key < a[mid]: high = mid - 1
else: low = mid + 1
return -1 (not found)
Example. Array: 5, 12, 18, 23, 34, 45, 56 (indices 0 to 6). Search key = 45.
| Step | low | high | mid | a[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 23 | 45 > 23, low = 4 |
| 2 | 4 | 6 | 5 | 45 | found at index 5 |
The key is found after 2 comparisons instead of 6 for linear search.
Complexity: the range is halved on every step, so the time is in the worst case and in the best case; space is for the iterative version.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 8 marks
What is heap? Use the following data and explain how heap is used to implement priority queue: 20,62,98,47,45,35,56,74.
Answer
Heap. A heap is a complete binary tree that satisfies the heap property: in a max heap every parent is greater than or equal to its children (so the root is the largest), and in a min heap every parent is less than or equal to its children. It is stored in an array, with the children of index at and .
Heap as a priority queue. In a priority queue the element with the highest priority is served first. A max heap does this efficiently: the highest priority is always at the root, insert adds the element at the end and moves it up (percolate up), and deleteMax removes the root, moves the last element to the root and moves it down (percolate down). Both take and finding the top item takes .
Building the max heap by inserting 20, 62, 98, 47, 45, 35, 56, 74:
| Insert | Heap array |
|---|---|
| 20 | [20] |
| 62 | 62 > 20 swap: [62, 20] |
| 98 | 98 > 62 swap: [98, 20, 62] |
| 47 | 47 > 20 swap: [98, 47, 62, 20] |
| 45 | [98, 47, 62, 20, 45] |
| 35 | [98, 47, 62, 20, 45, 35] |
| 56 | [98, 47, 62, 20, 45, 35, 56] |
| 74 | placed under 20: swap with 20, then with 47 (74 > 47), stop below 98: [98, 74, 62, 47, 45, 35, 56, 20] |
98
/ \
74 62
/ \ / \
47 45 35 56
/
20
Serving (dequeue) the highest priority. deleteMax returns 98. Move the last element 20 to the root: [20, 74, 62, 47, 45, 35, 56]. Swap with the larger child 74, then with the larger child 47: [74, 47, 62, 20, 45, 35, 56]. The next element served is therefore 74, then 62, and so on, so the elements leave in order of priority: 98, 74, 62, 56, 47, 45, 35, 20.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
Why is it important to sort data? Explain with an example.
Answer
Sorting arranges data in a particular order (ascending or descending). It is important because:
- Faster searching: a sorted list can be searched with binary search in instead of for linear search.
- Easier processing: finding the minimum, maximum, median, duplicates or the k-th largest element becomes trivial in sorted data.
- Efficient algorithms: merging two sorted lists, database joins, and many algorithms (e.g. Kruskal's algorithm sorts the edges) depend on sorted input.
- Better presentation: data such as names in a directory, marks in a result sheet or products by price are easier to read and compare when sorted.
- Detecting duplicates and matching records is easier because equal items are adjacent.
Example. Suppose a list of 1,000,000 student roll numbers is unsorted. To find one roll number we may need up to 1,000,000 comparisons. If the list is sorted, binary search needs at most about comparisons. Similarly, for the marks 56, 89, 42, 73, the sorted list 42, 56, 73, 89 shows the lowest, highest and median marks immediately.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
What is Backtracking Algorithm? Explain with suitable example.
Answer
Backtracking is a general algorithmic technique that builds a solution step by step, one choice at a time, and abandons ("backtracks" from) a partial solution as soon as it is found that it cannot lead to a valid complete solution. It is a refined depth-first search over the solution space (a state-space tree) that prunes branches violating the constraints.
General procedure:
- Choose the next candidate for the current position.
- If it satisfies the constraints, place it and recurse to the next position.
- If the recursion fails (no valid candidate), undo the choice and try the next candidate.
- If all positions are filled, a solution is found.
Example: 4-Queens problem. Place 4 queens on a board so that no two attack each other (same row, column or diagonal).
- Place Q1 in row 1, column 1.
- Row 2: columns 1 and 2 are attacked; place Q2 in column 3.
- Row 3: column 1 (same column as Q1), column 2 (diagonal of Q2), column 3 (column), column 4 (diagonal of Q2) are all attacked, so there is no place. Backtrack: move Q2 to column 4.
- Row 3: place Q3 in column 2. Row 4: columns 1, 2, 3 are attacked or blocked and column 4 is attacked, so no place. Backtrack to Q3, which has no other position; backtrack to Q2, which has none; backtrack to Q1 and move it to column 2.
- Q1 at (1,2), Q2 at (2,4), Q3 at (3,1), Q4 at (4,3) is a valid solution.
Other examples: Sudoku, graph colouring, subset sum, maze solving and the Hamiltonian cycle problem. Worst-case time is exponential, but pruning makes it practical.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 5 marks
Write short notes on: Splay tree
Answer
Splay tree. A splay tree is a self-adjusting binary search tree in which every access (search, insert or delete) moves the accessed node to the root by a sequence of rotations called splaying. Recently used nodes stay near the root, which makes repeated access fast. No balance information is stored.
Splaying operations (let be the accessed node, its parent and its grandparent):
- Zig: is the root; do a single rotation at .
- Zig-zig: and are both left children or both right children; rotate over , then over .
- Zig-zag: is a left child and a right child (or vice versa); rotate twice, as in an AVL double rotation.
Insertion: insert as in a BST, then splay the new node to the root. Deletion: splay the node to the root, remove it, then join the two subtrees.
Complexity: a single operation can take , but the amortised cost is per operation. Advantages: simple, no extra storage, good for non-uniform access patterns. Disadvantage: the tree can be unbalanced and even reads change the structure.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 5 marks
Write short notes on: Bucket sort
Answer
Bucket sort is a distribution sort that works well when the input is uniformly distributed over a known range.
Algorithm:
- Create empty buckets, each covering an equal sub-range of the key values.
- Scatter: put each element into the bucket for its range.
- Sort each bucket (usually with insertion sort).
- Gather: concatenate the buckets in order.
Example: sort 0.78, 0.17, 0.39, 0.26, 0.72, 0.94 using 10 buckets (bucket holds ):
- Bucket 1: 0.17; bucket 2: 0.26; bucket 3: 0.39; bucket 7: 0.78, 0.72 (sorted to 0.72, 0.78); bucket 9: 0.94.
- Concatenate: 0.17, 0.26, 0.39, 0.72, 0.78, 0.94.
Complexity: average for uniformly distributed data; worst case when all elements fall in one bucket. It needs extra space and is stable if the bucket sort is stable.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
What is Abstract Data Types? Explain the stack ADT with example.
Answer
Abstract Data Type (ADT). An ADT is a mathematical model of a data structure that specifies the data it holds and the operations that can be performed on it, without saying how the data is stored or how the operations are implemented. The user sees only the interface (what it does); the implementation (how) is hidden, which gives abstraction, encapsulation and the freedom to change the implementation. Examples: list, stack, queue, set, map.
Stack ADT. A stack is a linear collection in which insertion and deletion happen only at one end, called the top. It follows the LIFO (Last In, First Out) principle.
Operations:
push(x): insert at the top (error "overflow" if full).pop(): remove and return the top element (error "underflow" if empty).peek()/top(): return the top element without removing it.isEmpty(),isFull(): test the state of the stack.
It can be implemented with an array or a linked list.
Example. Start with an empty stack and perform: push(10), push(20), push(30), pop(), push(40).
- After the three pushes the stack (bottom to top) is 10, 20, 30.
pop()removes and returns 30, leaving 10, 20.push(40)gives 10, 20, 40 with 40 at the top.
Applications: function call management, undo operations, expression evaluation and conversion, balanced parentheses checking, and depth-first search.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
What is asymptotic notation? Explain its type in detail. Which asymptotic notation is most frequently used and why?
Answer
Asymptotic notation is a mathematical way of describing how the running time or space of an algorithm grows with the input size when becomes very large, ignoring machine-dependent constants and lower-order terms.
Types
-
Big-O, : upper bound. if for some constants , and all . It gives the worst-case growth. Example: since for .
-
Big-Omega, : lower bound. for all . It describes the best-case growth. Example: .
-
Big-Theta, : tight bound. for all . It holds when is both and . Example: .
-
Little-o, : a strict upper bound ( grows strictly slower than ), e.g. .
-
Little-omega, : a strict lower bound, e.g. .
Most frequently used: Big-O. We usually quote Big-O because:
- it gives a guarantee that the algorithm will never be slower than the stated bound, i.e. the worst case, which matters for reliable performance;
- the worst case is often easier to compute than the average or best case;
- the best case (Omega) is rarely useful, since an algorithm is judged by how it behaves on bad inputs;
- it allows quick comparison of algorithms by order of growth, e.g. vs .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
Write a program to demonstrate enqueue and dequeue operations in a stack.
Answer
A queue (FIFO) can be built from two stacks. stack1 receives the new elements (enqueue) and stack2 is used for removal (dequeue): when stack2 is empty, all elements of stack1 are popped and pushed onto stack2, which reverses their order so that the oldest element is on the top.
#include <iostream>
using namespace std;
#define MAX 100
class Stack {
int arr[MAX];
int top;
public:
Stack() { top = -1; }
bool isEmpty() { return top == -1; }
bool isFull() { return top == MAX - 1; }
void push(int x) {
if (isFull()) { cout << "Stack overflow\n"; return; }
arr[++top] = x;
}
int pop() {
if (isEmpty()) { cout << "Stack underflow\n"; return -1; }
return arr[top--];
}
};
class Queue {
Stack s1, s2;
public:
void enqueue(int x) {
s1.push(x);
}
int dequeue() {
if (s2.isEmpty()) {
while (!s1.isEmpty())
s2.push(s1.pop());
}
if (s2.isEmpty()) {
cout << "Queue is empty\n";
return -1;
}
return s2.pop();
}
};
int main() {
Queue q;
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
cout << q.dequeue() << endl; // 10
cout << q.dequeue() << endl; // 20
q.enqueue(40);
cout << q.dequeue() << endl; // 30
cout << q.dequeue() << endl; // 40
return 0;
}
Output: 10, 20, 30, 40 (first in, first out). Enqueue is ; dequeue is amortized, since each element is moved between the stacks at most once.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
Write an algorithm to convert an infix to postfix expression. Also convert following infix to prefix expression.
Answer
Algorithm: infix to postfix (using a stack of operators)
- Create an empty operator stack and an empty output string.
- Scan the infix expression from left to right.
- If the symbol is an operand, append it to the output.
- If it is
(, push it on the stack. - If it is
), pop operators from the stack to the output until(is found; discard both parentheses. - If it is an operator, pop from the stack to the output every operator whose precedence is higher than that of the current one, or equal when the current one is left associative (for the right-associative
$/^, pop only higher precedence); then push the current operator. - After the whole expression is scanned, pop all remaining operators to the output.
Precedence (high to low): $ (exponent), then * and /, then + and -.
Infix to prefix of
Convert the sub-expressions step by step, writing operator first:
- gives
- gives
- gives
- gives
- the whole expression, with
$as the main operator, gives
Prefix expression:
(For comparison, its postfix form is .)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
Differentiate between binary tree and binary search tree. What are the different binary tree traversal techniques? Explain with examples.
Answer
Binary tree vs binary search tree
| Binary tree | Binary search tree (BST) |
|---|---|
| Every node has at most two children. | A binary tree with an ordering property. |
| No ordering condition on the values. | Left subtree keys < node key < right subtree keys, for every node. |
| Searching takes since nodes must be examined one by one. | Searching, insertion and deletion take , i.e. for a balanced tree. |
| Inorder traversal gives no particular order. | Inorder traversal gives keys in sorted order. |
| Used for expression trees, heaps, Huffman trees. | Used for dictionaries, searching and sorting. |
Binary tree traversal techniques. Consider the tree with root 50, left child 30 (children 20, 40) and right child 70 (children 60, 80).
50
/ \
30 70
/ \ / \
20 40 60 80
- Inorder (Left, Root, Right): 20, 30, 40, 50, 60, 70, 80 (sorted, since this is a BST).
- Preorder (Root, Left, Right): 50, 30, 20, 40, 70, 60, 80.
- Postorder (Left, Right, Root): 20, 40, 30, 60, 80, 70, 50.
- Level order (breadth first, using a queue): 50, 30, 70, 20, 40, 60, 80.
Each traversal visits every node once and takes time. Preorder is used to copy a tree, postorder to delete a tree, and inorder to list a BST in sorted order.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
Why B-Tree is needed? Create a B-Tree of order 5 from the following set of data: 8, 14, 2, 15, 3, 1, 16, 6, 5, 27, 37, 18, 25, 7, 13, 20, 22, 23, 24
Answer
Why a B-tree is needed. A B-tree is a balanced multiway search tree designed for data stored on disk. Disk access is far slower than memory access, so we want to reduce the number of disk reads. A B-tree node holds many keys and has many children, which makes the tree very shallow ( height), so a search, insertion or deletion needs only a few disk accesses. All leaves are on the same level, so performance is guaranteed, and nodes are kept at least half full, which uses space well. Databases and file systems use B-trees for this reason.
Rules for order 5: each node has at most 5 children (at most 4 keys); each non-root node has at least 3 children (at least 2 keys); keys inside a node are sorted. When a node gets a fifth key it overflows: the median key moves up to the parent and the node is split into two.
Construction for 8, 14, 2, 15, 3, 1, 16, 6, 5, 27, 37, 18, 25, 7, 13, 20, 22, 23, 24:
- Insert 8, 14, 2, 15: one node [2, 8, 14, 15].
- Insert 3: overflow [2, 3, 8, 14, 15]; median 8 goes up. Root [8]; leaves [2, 3] and [14, 15].
- Insert 1 and 16: [1, 2, 3] and [14, 15, 16]. Insert 6: [1, 2, 3, 6].
- Insert 5: overflow [1, 2, 3, 5, 6]; median 3 goes up. Root [3, 8]; leaves [1, 2], [5, 6], [14, 15, 16].
- Insert 27: [14, 15, 16, 27]. Insert 37: overflow; median 16 goes up. Root [3, 8, 16]; leaves [1, 2], [5, 6], [14, 15], [27, 37].
- Insert 18: [18, 27, 37]. Insert 25: [18, 25, 27, 37]. Insert 7: [5, 6, 7]. Insert 13: [13, 14, 15].
- Insert 20: overflow [18, 20, 25, 27, 37]; median 25 goes up. Root [3, 8, 16, 25]; leaves [1, 2], [5, 6, 7], [13, 14, 15], [18, 20], [27, 37].
- Insert 22: [18, 20, 22]. Insert 23: [18, 20, 22, 23].
- Insert 24: leaf overflows [18, 20, 22, 23, 24]; median 22 goes up to the root, making it [3, 8, 16, 22, 25], which overflows too. Its median 16 goes up and becomes the new root, and the node is split into [3, 8] and [22, 25].
Final B-tree:
[16]
/ \
[3, 8] [22, 25]
/ | \ / | \
[1,2] [5,6,7] [13,14,15] [18,20] [23,24] [27,37]
All leaves are at the same level, and the tree has height 3.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
What is hashing and why is it important? Construct a hash table of size 10 for the following data using an appropriate hash function 7, 2, 18, 28, 38, 78, 15, 75. Resolve the collision if any using linear probing.
Answer
Hashing. Hashing is a technique that maps a key to an index of a table using a hash function, so that a record can be stored and found directly without searching through all elements. It is important because it gives average time for insertion, search and deletion, which is much faster than linear search () or binary search (). It is used in databases, symbol tables of compilers, caches and password storage.
Hash function: with table size 10. Linear probing resolves a collision by trying the next slot: for
Insertions:
- 7: , so slot 7.
- 2: slot 2.
- 18: slot 8.
- 28: is full; slot 9 is free, so slot 9.
- 38: full, 9 full, slot 0 free, so slot 0.
- 78: full, 9 full, 0 full, slot 1 free, so slot 1.
- 15: slot 5.
- 75: full, slot 6 free, so slot 6.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Key | 38 | 78 | 2 | 15 | 75 | 7 | 18 | 28 |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
Define binomial queue. Show the creation of a ascending heap of size 8 from the data 32, 58, 9, 30, 11, 67, 3, 14
Answer
Binomial queue. A binomial queue is a priority queue made of a forest of binomial trees, at most one of each order. A binomial tree is a single node, and is formed by attaching one as a child of the root of another ; has nodes. Every tree is heap ordered (parent smaller than children in a min queue). A queue with elements contains the tree exactly when bit of the binary form of is 1. Merge, insert and deleteMin take time.
Binomial queue for 32, 58, 9, 30, 11, 67, 3, 14 (inserting one by one; equal-order trees are merged, the larger root being attached under the smaller root):
- 32 gives . Insert 58: merge into (32 with child 58).
- Insert 9: queue is (9) and (32-58). Insert 30: 9 and 30 merge to (9-30), which merges with (32-58) to with root 9 and children 30 and 32(58).
- Insert 11: (11) and . Insert 67: 11 and 67 merge to (11-67); queue is and .
- Insert 3: (3), , . Insert 14: 3 and 14 merge to (3-14), merge with (11-67) to with root 3, then merge with (root 9) to .
The 8 elements () form the single tree with root 3 and children 14, 11 (with child 67) and 9 (with children 30 and 32(58)).
Ascending (min) heap of size 8 built by successive insertion, percolating each new element up:
| Insert | Array |
|---|---|
| 32 | [32] |
| 58 | [32, 58] |
| 9 | swap with 32: [9, 58, 32] |
| 30 | swap with 58: [9, 30, 32, 58] |
| 11 | swap with 30: [9, 11, 32, 58, 30] |
| 67 | [9, 11, 32, 58, 30, 67] |
| 3 | swap with 32, then with 9: [3, 11, 9, 58, 30, 67, 32] |
| 14 | swap with 58 (14 > 11 stop): [3, 11, 9, 14, 30, 67, 32, 58] |
3
/ \
11 9
/ \ / \
14 30 67 32
/
58
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
Explain how divide and conquer strategy is used to sort a list of data using Merge sort.
Answer
Merge sort sorts a list using the divide and conquer strategy.
- Divide: split the list of elements into two halves of about elements each.
- Conquer: sort each half recursively; a list of 0 or 1 element is already sorted (base case).
- Combine: merge the two sorted halves into one sorted list by repeatedly taking the smaller of the two front elements.
Algorithm
mergeSort(a, low, high):
if low < high:
mid = (low + high) / 2
mergeSort(a, low, mid)
mergeSort(a, mid + 1, high)
merge(a, low, mid, high)
Example: sort 38, 27, 43, 3, 9, 82, 10.
- Divide: [38, 27, 43, 3 | 9, 82, 10], then [38, 27 | 43, 3 | 9, 82 | 10], then to single elements.
- Merge: [27, 38], [3, 43], [9, 82], [10].
- Merge: [3, 27, 38, 43] and [9, 10, 82].
- Merge: [3, 9, 10, 27, 38, 43, 82].
Complexity. The recurrence is , which gives in the best, average and worst cases. It needs extra space for merging and is stable. It is also well suited to external sorting.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
What are the real life applications of the shortest path algorithm? Given the weighted directed graph, use Dijkstra Algorithm to find the shortest path from vertex A. (Weighted directed graph given in the paper with vertices A to H.)
Answer
Real life applications of shortest path algorithms
- GPS and map navigation (shortest or fastest route between two places).
- Network routing protocols such as OSPF, which find the least-cost path for data packets.
- Airline and transport scheduling, and logistics and delivery route planning.
- Social networks (degrees of separation) and game AI path finding.
- Telecommunication and VLSI circuit design, and robot motion planning.
Dijkstra's algorithm. It finds the shortest paths from a source vertex to all other vertices in a graph with non-negative weights. Set the distance of the source to 0 and all others to infinity; repeatedly select the unvisited vertex with the smallest distance, mark it final, and relax the edges leaving it (update if ).
Since the figure is not reproduced here, take the directed graph with edges: A→B = 4, A→C = 2, C→B = 1, C→E = 10, B→D = 5, D→E = 2, D→G = 9, E→F = 3, F→H = 4, G→H = 2. Source = A.
| Step | Vertex chosen | A | B | C | D | E | F | G | H |
|---|---|---|---|---|---|---|---|---|---|
| 0 | A (0) | 0 | 4 | 2 | inf | inf | inf | inf | inf |
| 1 | C (2) | 0 | 3 | 2 | inf | 12 | inf | inf | inf |
| 2 | B (3) | 0 | 3 | 2 | 8 | 12 | inf | inf | inf |
| 3 | D (8) | 0 | 3 | 2 | 8 | 10 | inf | 17 | inf |
| 4 | E (10) | 0 | 3 | 2 | 8 | 10 | 13 | 17 | inf |
| 5 | F (13) | 0 | 3 | 2 | 8 | 10 | 13 | 17 | 17 |
| 6 | G (17) | 0 | 3 | 2 | 8 | 10 | 13 | 17 | 17 |
| 7 | H (17) | final |
Shortest distances and paths from A:
- B = 3 (A-C-B)
- C = 2 (A-C)
- D = 8 (A-C-B-D)
- E = 10 (A-C-B-D-E)
- F = 13 (A-C-B-D-E-F)
- G = 17 (A-C-B-D-G)
- H = 17 (A-C-B-D-E-F-H)
Complexity: with an array, with a binary heap.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 5 marks
Write short notes on: Dynamic programming
Answer
Dynamic programming (DP) is an algorithm design technique for optimisation problems whose solution can be built from solutions of smaller subproblems. It applies when a problem has:
- Optimal substructure: an optimal solution contains optimal solutions of its subproblems.
- Overlapping subproblems: the same subproblems occur again and again.
Each subproblem is solved once and its answer is stored in a table, so it is never recomputed. There are two styles: top-down with memoization (recursion plus a cache) and bottom-up tabulation (filling a table from the smallest subproblems upward).
Example: Fibonacci numbers. The plain recursion fib(n) = fib(n-1) + fib(n-2) takes exponential time because it recomputes the same values. With a table, f[0]=0, f[1]=1, f[i]=f[i-1]+f[i-2] is computed in time.
Other classic problems: 0/1 knapsack, longest common subsequence, matrix-chain multiplication, shortest paths (Floyd-Warshall) and coin change.
Difference from divide and conquer: subproblems in divide and conquer are independent, while in DP they overlap and their results are reused.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 5 marks
Write short notes on: Backtracking algorithm
Answer
Backtracking is a systematic trial-and-error technique for solving problems with constraints. A solution is built one component at a time; after each choice, a feasibility test checks whether the partial solution can still lead to a full solution. If it cannot, the last choice is undone (the algorithm backtracks) and the next alternative is tried. It is a depth-first search of the state-space tree with pruning of hopeless branches.
Outline
solve(k):
if solution complete: report it
else for each candidate c for position k:
if c is feasible:
place c; solve(k + 1); remove c
Examples: N-Queens problem, Sudoku, rat in a maze, graph colouring, subset sum and Hamiltonian cycle.
Example (4-Queens): put a queen in each row so that no two share a column or diagonal. If a row has no safe column, go back to the previous row and move its queen; the solution (2, 4, 1, 3) is found this way.
Features: guarantees finding a solution if one exists (or reports none) and prunes the search space, but the worst-case time is still exponential.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 5 marks
Write short notes on: Quick sort
Answer
Quick sort is a divide-and-conquer sorting algorithm.
- Choose a pivot element (first, last, middle or random).
- Partition: rearrange the array so that elements smaller than the pivot are to its left and larger ones to its right; the pivot is then in its final sorted position.
- Recurse on the left and right parts.
Example: 30, 10, 50, 20, 40 with the first element as pivot. Partitioning around 30 gives 20, 10, 30, 50, 40. Sorting the left part gives 10, 20 and the right part gives 40, 50. Result: 10, 20, 30, 40, 50.
Complexity
- Best and average case: .
- Worst case: , when the pivot is always the smallest or largest element (e.g. sorted input with the first element as pivot).
- Space: for the recursion stack.
It is an in-place sort that is not stable. In practice it is usually faster than merge sort because of good cache behaviour and small constants, and randomised pivot selection makes the worst case unlikely.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from PU BCA 2025 Spring (New) Data Structure and Algorithms (Pokhara University BCA, Spring 2025), PU BCA 2024 Fall (New) Data Structure and Algorithms (Pokhara University BCA, Fall 2024), PU BCA 2024 Spring Data Structure and Algorithms (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring Data Structure and Algorithms (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall Data Structure and Algorithms (Pokhara University BCA, Fall 2022), PU BCA 2025 Spring Object Oriented Programming using Java (Pokhara University BCA, Spring 2025), PU BCA 2024 Fall Object Oriented Programming using Java (Pokhara University BCA, Fall 2024), PU BCA 2024 Spring Java Programming (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring Java Programming (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall Java Programming (Pokhara University BCA, Fall 2022), PU BCA 2025 Spring (New) Operating System (Pokhara University BCA, Spring 2025), PU BCA 2024 Fall (New) Operating System (Pokhara University BCA, Fall 2024), PU BCA 2024 Spring Operating System (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring Operating System (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall Operating System (Pokhara University BCA, Fall 2022), PU BCA 2021 Spring Operating System (Pokhara University BCA, Spring 2021), PU BCA 2025 Spring System Analysis and Project Management (Pokhara University BCA, Spring 2025), PU BCA 2024 Spring System Analysis and Design (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring System Analysis and Design (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall System Analysis and Design (Pokhara University BCA, Fall 2022), PU BCA 2025 Spring (New) Web Technologies I (Pokhara University BCA, Spring 2025, new syllabus), PU BCA 2025 Spring Web Technologies I (Pokhara University BCA, Spring 2025), PU BCA 2024 Spring Web Technologies I (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring Web Technologies I (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall Web Technologies I (Pokhara University BCA, Fall 2022) and PU BCA 2021 Spring Web Technologies I (Pokhara University BCA, Spring 2021). Answers are written for this site; check them against your class notes.