Chapter 1
Data Structures and Algorithms
TU BCA past exam questions
Past questions and answers
79 questions set from this chapter, 1 of them more than once. Most repeated first.
- Asked 2 times
- 2022 · 5 marks
- 2025 · 5 marks
What is hashing? Describe the types of collision resolution techniques with suitable example.
Answer
Hashing is a technique that maps a key to an index of a table (hash table) by a hash function, for example , so that insertion, search and deletion take time on average. When two keys map to the same index a collision occurs, and a collision resolution technique is needed.
Types of collision resolution
1. Separate chaining (open hashing). Each slot holds a linked list of all keys that hash to it. Keys 15, 25, 35 with all go to index 5 and form the chain .
2. Open addressing (closed hashing). All keys are stored in the table itself; on collision another empty slot is found by probing.
Example: , , keys 23, 43, 13, 27 (23, 43, 13 all hash to 3, and 27 to 7).
- Linear probing: try for . 23 at index 3; 43 at 4; 13 at 5; 27 at 7. Drawback: primary clustering.
- Quadratic probing: try . 23 at 3; 43 goes to ; 13: index 4 is full, so ; 27: index 7 is full, so . Reduces primary clustering but may cause secondary clustering.
- Double hashing: try with, say, . 23 at 3; 43: , so ; 13: , so ; 27 at 7. Gives the best distribution.
Other: rehashing (building a larger table when the load factor becomes high).
Chaining never overflows and handles deletion easily but uses extra pointer memory; open addressing saves memory but needs a load factor below 1 and careful deletion.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
What is Data Structure? Show the status of stack converting following infix expression to postfix: P + Q - (RS/T+U)-VW
Answer
A data structure is a particular way of organising and storing data in memory so that it can be accessed and modified efficiently. It specifies the data items, the relationships between them and the operations allowed on them. Examples: array, stack, queue, linked list, tree, graph.
Infix to postfix using a stack
Expression: P + Q - (R * S / T + U) - V * W
Rules: an operand goes straight to the output; ( is pushed; on ) pop to the output until (; an operator first pops every stack operator of equal or higher precedence, then is pushed. At the end pop everything.
| Symbol | Stack (bottom to top) | Postfix output |
|---|---|---|
| P | P | |
| + | + | P |
| Q | + | P Q |
| - | - (pops +) | P Q + |
| ( | - ( | P Q + |
| R | - ( | P Q + R |
| * | - ( * | P Q + R |
| S | - ( * | P Q + R S |
| / | - ( / (pops *) | P Q + R S * |
| T | - ( / | P Q + R S * T |
| + | - ( + (pops /) | P Q + R S * T / |
| U | - ( + | P Q + R S * T / U |
| ) | - (pops + and removes "(") | P Q + R S * T / U + |
| - | - (pops -) | P Q + R S * T / U + - |
| V | - | P Q + R S * T / U + - V |
| * | - * | P Q + R S * T / U + - V |
| W | - * | P Q + R S * T / U + - V W |
| end | empty (pops * then -) | P Q + R S * T / U + - V W * - |
Postfix: PQ+RS*T/U+-VW*-
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
Write binary search. Consider a hash table of size 10; insert the keys 62, 37, 36, 44, 67, 91 and 107 using linear probing.
Answer
Binary search
Binary search finds a key in a sorted array by repeatedly comparing it with the middle element and discarding half of the remaining range.
BinarySearch(A, n, key)
1. low = 0, high = n - 1
2. while low <= high
3. mid = (low + high) / 2
4. if A[mid] == key return mid
5. else if key < A[mid] high = mid - 1
6. else low = mid + 1
7. return -1 // not found
Each step halves the range, so the time is (best case ).
Hash table of size 10 with linear probing
Hash function: . On a collision try for
| Key | Probing | Slot | |
|---|---|---|---|
| 62 | 2 | free | 2 |
| 37 | 7 | free | 7 |
| 36 | 6 | free | 6 |
| 44 | 4 | free | 4 |
| 67 | 7 | 7 full, try 8 | 8 |
| 91 | 1 | free | 1 |
| 107 | 7 | 7, 8 full, try 9 | 9 |
Final table:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Key | 91 | 62 | 44 | 36 | 37 | 67 | 107 |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
What are deterministic and non-deterministic algorithms? Explain greedy algorithm.
Answer
Deterministic algorithm: at every step the next operation is uniquely defined, so for the same input it always follows the same sequence of steps and gives the same output. Examples: binary search, merge sort, Dijkstra's algorithm.
Non-deterministic algorithm: some steps allow several possible choices, and the algorithm is assumed to "guess" the correct choice (as if it could try all in parallel), so the same input may follow different execution paths. It uses operations such as choice(), failure() and success(). It is a theoretical model used to define the class NP (problems whose solution can be verified in polynomial time), e.g. searching, the travelling salesman decision problem.
| Deterministic | Non-deterministic |
|---|---|
| One outcome for each step | Several possible outcomes at a step |
| Practically executable | Theoretical model (simulated by trying all choices) |
| Class P | Class NP |
Greedy algorithm
A greedy algorithm builds the solution step by step and at every step selects the choice that looks best at that moment (locally optimal), never reconsidering earlier choices, hoping to reach a globally optimal solution.
Features: a candidate set, a selection function, a feasibility check and an objective function. It is fast and simple, but gives an optimal answer only for problems having the greedy-choice property and optimal substructure.
Examples: Kruskal's and Prim's minimum spanning tree, Dijkstra's shortest path, Huffman coding, fractional knapsack, activity selection.
Example (coin change with Rs 1, 2, 5, 10 coins): to pay Rs 28, repeatedly take the largest coin that fits: 10 + 10 + 5 + 2 + 1, giving 5 coins, which is optimal for this coin system.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
Draw a BST from the string DATASTRUCTURE and traverse the tree in post order and preorder.
Answer
Constructing the BST from DATASTRUCTURE
Letters in order: D, A, T, A, S, T, R, U, C, T, U, R, E. A BST holds distinct keys, so repeated letters (A, T, U, R, T, U) are ignored after their first insertion. Rule: smaller goes left, larger goes right.
- D is the root.
- A < D, left of D.
- T > D, right of D.
- S: > D, < T, so left of T.
- R: > D, < T, < S, so left of S.
- U: > D, > T, so right of T.
- C: < D, > A, so right of A.
- E: > D, < T, < S, < R, so left of R.
D
/ \
A T
\ / \
C S U
/
R
/
E
Preorder (Root, Left, Right): D A C T S R E U
Postorder (Left, Right, Root): C A E R S U T D
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
Define circular queue? How does circular queue overcome the limitation of linear queue? Explain.
Answer
Circular queue: a queue in which the last position is logically connected back to the first position, so the array is treated as a circle. Elements are inserted at rear and removed from front, and both indices wrap around using modulo arithmetic:
Limitation of the linear queue: in an array-based linear queue, rear only moves forward. After some deletions the freed cells at the front can never be reused, so rear == SIZE - 1 reports "queue full" even though empty cells exist. Example: SIZE = 5, insert 5 items and delete 3. Only 2 items are present but no insertion is possible. The only remedy is shifting all elements, which costs .
How the circular queue overcomes it: when rear reaches the last index, the next insertion goes to index 0 if that cell is free, so every empty cell is reused. The queue is full only when all SIZE cells are occupied, that is when (one cell is often left unused to tell full from empty). It is empty when front == -1 (or front == rear in the sacrificed-cell version). Both enqueue and dequeue stay and memory is used efficiently.
In the example above (SIZE = 5, 2 items remaining), the next insertions simply wrap to indices 0, 1, 2.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
What is singly linked list? Write an algorithm to add a node at the beginning and end of Singly linked list.
Answer
A singly linked list is a linear collection of nodes in which each node has a data field and one pointer next to the following node. A pointer head holds the first node, and the last node's next is NULL. Traversal is possible only in the forward direction.
struct node {
int data;
struct node *next;
};
Insert at the beginning
InsertBegin(head, item)
1. Create newnode; if memory not available, print "overflow" and stop
2. newnode->data = item
3. newnode->next = head
4. head = newnode
struct node* insertBegin(struct node *head, int item) {
struct node *n = (struct node*)malloc(sizeof(struct node));
n->data = item;
n->next = head;
return n; /* new head */
}
Insert at the end
InsertEnd(head, item)
1. Create newnode; newnode->data = item; newnode->next = NULL
2. if head == NULL then head = newnode and stop
3. temp = head
4. while temp->next != NULL: temp = temp->next
5. temp->next = newnode
struct node* insertEnd(struct node *head, int item) {
struct node *n = (struct node*)malloc(sizeof(struct node));
n->data = item;
n->next = NULL;
if (head == NULL) return n;
struct node *temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = n;
return head;
}
Insertion at the beginning takes ; insertion at the end takes because the list must be traversed (it is if a tail pointer is kept).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 5 marks
Define AVL tree. Construct AVL tree from given data set:
4, 6, 12, 9, 5, 2, 13, 8, 3, 7, 11.
Answer
AVL tree: a self-balancing binary search tree in which, for every node, the balance factor is , or . When an insertion makes some node's BF become , the tree is restored by a rotation (LL, RR, LR or RL), so the height stays and search, insert and delete are all .
Construction for 4, 6, 12, 9, 5, 2, 13, 8, 3, 7, 11 (a tree is written as root(left, right)):
| Insert | Tree after insertion | Action |
|---|---|---|
| 4 | 4 | |
| 6 | 4(-, 6) | |
| 12 | 4 has BF (RR case) | left rotation at 4, giving 6(4, 12) |
| 9 | 6(4, 12(9, -)) | balanced |
| 5 | 6(4(-, 5), 12(9, -)) | balanced |
| 2 | 6(4(2, 5), 12(9, -)) | balanced |
| 13 | 6(4(2, 5), 12(9, 13)) | balanced |
| 8 | 6(4(2, 5), 12(9(8, -), 13)) | balanced |
| 3 | 6(4(2(-, 3), 5), 12(9(8, -), 13)) | balanced |
| 7 | 9 has BF (LL case) | right rotation at 9, giving 12(8(7, 9), 13) |
| 11 | 12 has BF , its left child 8 has BF (LR case) | left rotation at 8, then right rotation at 12, giving 9(8(7, -), 12(11, 13)) |
Final AVL tree
6
/ \
4 9
/ \ / \
2 5 8 12
\ / / \
3 7 11 13
Check: BF(6) = 3 - 3 = 0, BF(4) = 2 - 1 = 1, BF(9) = 2 - 2 = 0, BF(12) = 0, so every node is within .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 10 marks
What is stack? List the applications of stack. Write an algorithm or procedure to perform PUSH and POP operation in stack.
Answer
Stack: a linear data structure in which insertion (PUSH) and deletion (POP) are done at only one end, called the top. It follows the LIFO (Last In First Out) principle: the element inserted last is removed first. It is an ADT with operations push, pop, peek/top, isEmpty and isFull.
Applications of stack
- Function call management and recursion (call stack)
- Conversion of infix expressions to postfix or prefix
- Evaluation of postfix and prefix expressions
- Matching parentheses and syntax checking in compilers
- Reversing a string or list
- Undo/redo in editors and back button in browsers
- Depth first search of graphs and backtracking (maze, N-queens)
- Tower of Hanoi
Array implementation (stack[MAX], top = -1 initially)
PUSH(stack, item)
1. if top == MAX - 1
2. print "Stack overflow" and stop
3. top = top + 1
4. stack[top] = item
POP(stack)
1. if top == -1
2. print "Stack underflow" and stop
3. item = stack[top]
4. top = top - 1
5. return item
#define MAX 100
int stack[MAX], top = -1;
void push(int item) {
if (top == MAX - 1) { printf("Stack overflow\n"); return; }
stack[++top] = item;
}
int pop(void) {
if (top == -1) { printf("Stack underflow\n"); return -1; }
return stack[top--];
}
Both operations take time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 10 marks
What is heap? Explain quick sort algorithm with Big-oh notation in best case, average case and worst case and trace it to sort the data: 8, 10, 5, 12, 14, 5, 7, 13.
Answer
Heap: a complete binary tree that satisfies the heap property. In a max-heap every parent is greater than or equal to its children (the root is the largest); in a min-heap every parent is less than or equal to its children (the root is the smallest). It is usually stored in an array, where the children of index are and . Heaps are used for heap sort and priority queues.
Quick sort
Quick sort is a divide and conquer sorting method.
- Choose a pivot (here the first element).
- Partition: rearrange so that elements pivot are on its left and elements pivot on its right; the pivot is then in its final position.
- Recursively sort the left and right parts.
QuickSort(A, low, high)
1. if low < high
2. p = Partition(A, low, high)
3. QuickSort(A, low, p - 1)
4. QuickSort(A, p + 1, high)
Partition(A, low, high)
1. pivot = A[low], i = low + 1, j = high
2. repeat
3. while i <= high and A[i] <= pivot: i = i + 1
4. while A[j] > pivot: j = j - 1
5. if i < j swap A[i], A[j]
6. until i >= j
7. swap A[low], A[j]
8. return j
Complexity (Big-Oh)
| Case | Time | When |
|---|---|---|
| Best | pivot splits the array into two equal halves each time | |
| Average | random data | |
| Worst | already sorted data (pivot is always the smallest or largest) |
Space is for the recursion stack (average).
Trace for 8, 10, 5, 12, 14, 5, 7, 13
- Pivot 8: i stops at 10, j stops at 7, swap: 8 7 5 12 14 5 10 13. i stops at 12, j stops at the second 5, swap: 8 7 5 5 14 12 10 13. Now i (at 14) has crossed j (at 5), so swap pivot with A[j]: 5 7 5 8 14 12 10 13. Pivot 8 is fixed.
- Left part 5 7 5, pivot 5: i stops at 7, j stops at the last 5, swap: 5 5 7. Then pointers cross; pivot swaps with itself or the equal 5: 5 5 7.
- Right part 14 12 10 13, pivot 14: i runs off the end, j stops at 13 (13 is not greater than 14); swap pivot with 13: 13 12 10 14. 14 is fixed.
- Part 13 12 10, pivot 13: result 10 12 13.
- Part 10 12, pivot 10 already in place; 12 alone.
Combining: 5 5 7 8 10 12 13 14.
Sorted output: 5, 5, 7, 8, 10, 12, 13, 14
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 10 marks
Define graph and tree data structure. Explain breadth first traversal and depth first traversal with example.
Answer
Graph: a non-linear data structure consisting of a set of vertices (nodes) and a set of edges connecting pairs of vertices. Edges may be directed or undirected, weighted or unweighted, and a graph may contain cycles.
Tree: a non-linear hierarchical data structure that is a connected graph without cycles. It has one special node, the root, and every other node has exactly one parent. A tree with nodes has edges. Every tree is a graph, but not every graph is a tree.
Example graph (undirected): vertices A, B, C, D, E, F with edges A-B, A-C, B-D, B-E, C-F, E-F.
Adjacency lists: A: B, C; B: A, D, E; C: A, F; D: B; E: B, F; F: C, E.
Breadth first traversal (BFS)
It visits all vertices at distance 1 from the start, then distance 2, and so on, using a queue.
BFS(start)
1. mark start visited; enqueue(start)
2. while queue not empty
3. v = dequeue(); visit v
4. for each unvisited neighbour w of v: mark w visited; enqueue(w)
Trace from A: queue [A] → visit A, add B, C → visit B, add D, E → visit C, add F → visit D → visit E → visit F.
BFS order: A, B, C, D, E, F. Time .
Depth first traversal (DFS)
It goes as deep as possible along a path before backtracking, using a stack (or recursion).
DFS(v)
1. mark v visited; visit v
2. for each unvisited neighbour w of v: DFS(w)
Trace from A: A → B → D (dead end, backtrack to B) → E → F → C (A is already visited, backtrack all the way).
DFS order: A, B, D, E, F, C. Time .
BFS finds shortest paths in unweighted graphs; DFS is used for cycle detection, topological sorting and connected components.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
What is the measurement for time complexity of an algorithm?
(a) Counting microseconds
(b) Counting kilobytes of algorithms
(c) Counting number of key operations
(d) Counting number of statements
Answer
(c) Counting number of key operations
Time complexity measures how the number of basic (key) operations grows with the input size $, independent of machine speed, so it is not measured in microseconds, kilobytes or statement count.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
Which of the following is the result of evaluation of 5 7 4 - * 8 4 / +?
(a) 5
(b) 8
(c) 10
(d) 17
Answer
(d) 17
Evaluate the postfix expression using a stack: push 5, 7, 4; - gives ; * gives ; push 8, 4; / gives ; + gives .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
What is the recursive formula for post order traversal of binary tree?
(a) Left-Root-Right
(b) Root-Left-Right
(c) Left-Right-Root
(d) Right-Left-Root
Answer
(c) Left-Right-Root
In postorder traversal the left subtree is visited first, then the right subtree, and the root last.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
What is the number of disk movement in TOH with 4 disks?
(a) 9
(b) 14
(c) 17
(d) 15
Answer
(d) 15
The Tower of Hanoi with disks needs moves, so for 4 disks .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
What is the Big-Oh of best case complexity of insertion sort?
(a) O(n)
(b) O(nlogn)
(c) O(1)
(d) O(n^2)
Answer
(a) O(n)
For already sorted input each element is compared once with its predecessor and no shifting is needed, so the best case takes comparisons, which is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
How does the rear index incremented in circular queue?
(a) front=(rear+1)%SIZE
(b) rear=(rear+1)%SIZE
(c) rear=rear+1
(d) rear=(rear-1)%SIZE
Answer
(b) rear=(rear+1)%SIZE
The modulo makes rear wrap round to index 0 after the last index, which is what makes the queue circular.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
A variation of linked list in which none of the node contains NULL pointer is ......
(a) Singly
(b) Multiple
(c) Circular
(d) Doubly
Answer
(c) Circular
In a circular linked list the last node points back to the first node, so no node has a NULL pointer.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
Which of the following data structure is used in depth first search of graph?
(a) Stack
(b) Queue
(c) Linked List
(d) None of the above
Answer
(a) Stack
DFS goes deep and then backtracks, which is last-in first-out behaviour, so it uses a stack (or the recursion call stack). BFS uses a queue.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
Which of the following is true for B-Tree of order M?
(a) Leaf nodes should be at different level
(b) All the key values within a node must be in descending order
(c) Every node has at least M children
(d) All non-leaf nodes with M-1 keys must have M number of children
Answer
(d) All non-leaf nodes with M-1 keys must have M number of children
In a B-tree of order an internal node with keys has children, so a node with keys has children. All leaves are at the same level, keys within a node are in ascending order, and a node needs at least children (not ) except the root.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 · 1 mark
Which of the following is not a hash function?
(a) Division remainder
(b) Folding
(c) Chaining
(d) Mid square
Answer
(c) Chaining
Division remainder, folding and mid-square are hash functions that compute an address from a key. Chaining is a collision resolution technique, not a hash function.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
What is Data Structure? Explain different operations to be performed on data structure.
Answer
A data structure is a systematic way of organising, storing and managing data in a computer so that it can be used efficiently. It defines the data elements, how they are related, and the operations that can be applied to them. Data structures are classified as primitive (int, char, float) and non-primitive; non-primitive ones are linear (array, stack, queue, linked list) and non-linear (tree, graph).
Operations performed on a data structure
- Traversing: visiting every element exactly once to process it, e.g. printing all items of an array or list.
- Searching: finding the location of an element with a given key (linear search, binary search), or finding that it is absent.
- Insertion: adding a new element at a given position, e.g. push into a stack, enqueue into a queue, adding a node to a list.
- Deletion: removing an existing element, e.g. pop, dequeue, deleting a node.
- Sorting: arranging the elements in ascending or descending order (bubble, insertion, quick, merge, heap sort).
- Merging: combining two sorted structures into a single sorted structure.
- Updating (modification): changing the value of an existing element.
- Copying/Splitting and creating or destroying the structure are also performed in some cases.
For example, in an array A[5] = {3, 8, 1, 9, 4}: traversing prints all five values, searching 9 returns index 3, inserting 7 at index 2 shifts the following elements right, and deleting index 0 shifts the others left.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
Define Greedy Algorithm and heuristic algorithm. Briefly explain Big-Oh Notation.
Answer
Greedy algorithm: an algorithm that builds a solution step by step, always choosing the option that looks best at that moment (locally optimal) without reconsidering earlier choices, in the hope of reaching the global optimum. It works when the problem has the greedy-choice property and optimal substructure. Examples: Kruskal's and Prim's MST, Dijkstra's algorithm, Huffman coding, fractional knapsack.
Heuristic algorithm: an algorithm that uses a rule of thumb or experience-based strategy to find a good, acceptable solution quickly, but without a guarantee that it is optimal or even always correct. It is used when an exact solution is too costly, e.g. the nearest-neighbour method for the travelling salesman problem, or the A* search heuristic.
| Greedy | Heuristic |
|---|---|
| Picks the best local choice at each step | Uses an estimate or rule of thumb |
| Optimal for some problems (with proof) | Usually gives only an approximate solution |
Big-Oh notation
Big-Oh gives an asymptotic upper bound on the growth rate of an algorithm's running time (usually the worst case). We write if there exist positive constants and such that
Example: for , take and : for , so .
Constants and lower order terms are ignored. Common orders, from fastest to slowest growth: . Examples: binary search , linear search , bubble sort .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
What is circular queue? Write an algorithm to insert an item in circular queue.
Answer
Circular queue: a queue implemented in an array in which the last position is treated as connected to the first, so after the last index the next position is index 0. Elements are added at rear and removed from front. This lets freed cells at the front be reused, which a linear queue cannot do.
Conditions (array Q[SIZE], initially front = -1, rear = -1):
- Full:
(rear + 1) % SIZE == front - Empty:
front == -1
Algorithm to insert an item
CQInsert(Q, SIZE, item)
1. if (rear + 1) % SIZE == front
2. print "Queue overflow" and stop
3. if front == -1 // first element
4. front = 0, rear = 0
5. else
6. rear = (rear + 1) % SIZE
7. Q[rear] = item
#define SIZE 5
int Q[SIZE], front = -1, rear = -1;
void enqueue(int item) {
if ((rear + 1) % SIZE == front) {
printf("Queue overflow\n");
return;
}
if (front == -1)
front = rear = 0;
else
rear = (rear + 1) % SIZE;
Q[rear] = item;
}
The insertion takes time. Example with SIZE = 5: if rear = 4 and front = 2, then , so the queue is not full, and the new item is stored at index 0.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
How does AVL tree differ from BST? Construct an AVL tree from following data:
35, 56, 68, 65, 44, 41, 31, 49, 20.
Answer
Difference between AVL tree and BST
| BST | AVL tree |
|---|---|
| Left keys smaller, right keys larger than the node | A BST that additionally keeps at every node |
| No balancing, so it can become skewed (height up to ) | Self-balancing by rotations, height always |
| Search, insert, delete are in the worst case | They are in the worst case |
| Simple insertion, no rotations | Extra work to store heights and perform rotations |
Construction for 35, 56, 68, 65, 44, 41, 31, 49, 20 (the tree is written as root(left, right), ):
| Insert | Tree | Action |
|---|---|---|
| 35 | 35 | |
| 56 | 35(-, 56) | |
| 68 | 35 has BF (RR) | left rotation at 35, giving 56(35, 68) |
| 65 | 56(35, 68(65, -)) | balanced |
| 44 | 56(35(-, 44), 68(65, -)) | balanced |
| 41 | 35 has BF , right child 44 has BF (RL) | right rotation at 44 then left rotation at 35, giving 56(41(35, 44), 68(65, -)) |
| 31 | 56(41(35(31, -), 44), 68(65, -)) | balanced |
| 49 | 56(41(35(31, -), 44(-, 49)), 68(65, -)) | balanced |
| 20 | 35 has BF (LL) | right rotation at 35, giving 31(20, 35) |
Final AVL tree
56
/ \
41 68
/ \ /
31 44 65
/ \ \
20 35 49
Check: BF(31) = 0, BF(41) = 2 - 2 = 0, BF(44) = -1, BF(68) = 1, BF(56) = 3 - 2 = 1, so the tree is a valid AVL tree.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
What is B-tree? Create a B-Tree of order 4 using following data:
6, 4, 22, 10, 2, 14, 3, 8, 11, 13, 5, 9.
Answer
B-tree: a self-balancing multiway search tree, widely used in databases and file systems to keep data sorted on disk. A B-tree of order has these properties:
- Every node has at most children and at most keys.
- Every non-root internal node has at least children; the root has at least 2 children (if it is not a leaf).
- A node with children holds keys in ascending order.
- All leaves are at the same level.
Search, insertion and deletion take time.
Insertion rule (order 4): a node holds at most 3 keys. Insert the key into the proper leaf; if the leaf then has 4 keys, split it: the second key moves up to the parent, the first key stays in the left node and the remaining two keys form the right node. A split may propagate upward.
Construction for 6, 4, 22, 10, 2, 14, 3, 8, 11, 13, 5, 9 (tree written as [root] with its children):
| Insert | Tree after insertion |
|---|---|
| 6, 4, 22 | [4 6 22] |
| 10 | leaf would be [4 6 10 22], split, 6 moves up: [6] with [4], [10 22] |
| 2 | [6] with [2 4], [10 22] |
| 14 | [6] with [2 4], [10 14 22] |
| 3 | [6] with [2 3 4], [10 14 22] |
| 8 | leaf [8 10 14 22], split, 10 moves up: [6 10] with [2 3 4], [8], [14 22] |
| 11 | [6 10] with [2 3 4], [8], [11 14 22] |
| 13 | leaf [11 13 14 22], split, 13 moves up: [6 10 13] with [2 3 4], [8], [11], [14 22] |
| 5 | leaf [2 3 4 5], split, 3 moves up: root would be [3 6 10 13] with 4 keys, so the root splits and 6 moves up to a new root |
| 9 | goes into leaf [8], giving [8 9] |
Final B-tree of order 4
[ 6 ]
/ \
[ 3 ] [ 10 13 ]
/ \ / | \
[ 2 ] [ 4 5 ] [ 8 9 ] [ 11 ] [ 14 22 ]
All leaves are at the same level, every node has at most 3 keys, and every internal node has one more child than keys.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
What is binary search? Write an algorithm to search an item using binary search.
Answer
Binary search is a searching technique for a sorted array. It repeatedly compares the key with the middle element and discards the half that cannot contain the key, so the search range halves at every step. It is a divide-and-conquer method with time complexity (best case ) and space in the iterative form.
Algorithm (BinarySearch(A, n, key))
- Set , .
- Repeat steps 3 to 5 while .
- Set .
- If , return (found) and stop.
- If , set ; otherwise set .
- Return (not found).
Example. , key .
| Step | low | high | mid | A[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 23 | , so |
| 2 | 4 | 6 | 5 | 40 | , so |
| 3 | 4 | 4 | 4 | 31 | found at index 4 |
C function
int binarySearch(int a[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == key) return mid;
else if (key < a[mid]) high = mid - 1;
else low = mid + 1;
}
return -1;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 5 marks
What is graph? Explain Kruskal's algorithm to construct minimum spanning tree with example.
Answer
Graph. A graph is a non-linear data structure consisting of a finite set of vertices (nodes) and a set of edges, each edge joining a pair of vertices. A graph may be directed or undirected, and weighted if each edge carries a cost. It is used to model networks such as roads, computer networks and social connections.
Kruskal's algorithm builds a minimum spanning tree (MST) of a connected, weighted, undirected graph by the greedy method: always take the cheapest remaining edge that does not form a cycle.
Steps
- Sort all edges in non-decreasing order of weight.
- Start with a forest in which every vertex is its own tree.
- Take the next smallest edge. If its end points are in different trees, add it to the MST and merge the trees; otherwise discard it (it would form a cycle).
- Stop when edges have been chosen.
Complexity is , dominated by sorting.
Example. Vertices A to F 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.
| Edge (sorted) | Weight | Decision |
|---|---|---|
| B-C | 1 | accept |
| A-C | 2 | accept |
| D-E | 2 | accept |
| E-F | 3 | accept |
| A-B | 4 | reject (A and B already connected through C) |
| B-D | 5 | accept (joins {A,B,C} with {D,E,F}) |
Five edges () are chosen, so the algorithm stops. The MST edges are B-C, A-C, D-E, E-F, B-D and
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 10 marks
Define stack. List the applications of stack. Trace the algorithm to convert infix to postfix with following infix expression: ((A + B) - C * D/E)*(H-I)*F+G and evaluate the obtained postfix expression with following values: A = 4, B = 2, C = 4, D = 3, E = 8, F = 2, G = 3, H = 5, I = 1.
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) principle.
Applications of stack
- Conversion and evaluation of expressions (infix, postfix, prefix).
- Function calls and recursion (call stack).
- Undo/redo in editors and back button in browsers.
- Parenthesis matching and syntax checking in compilers.
- Reversing a string or list, and depth first search.
Infix to postfix. Expression: .
Rules: operands go straight to output; an operator pops operators of higher or equal precedence from the stack first; ( is pushed, and ) pops until (. Precedence: * and / above + and -.
| Symbol | Stack (bottom to top) | Output |
|---|---|---|
| ( | ( | |
| ( | ( ( | |
| A | ( ( | A |
| + | ( ( + | A |
| B | ( ( + | AB |
| ) | ( | AB+ |
| - | ( - | AB+ |
| C | ( - | AB+C |
| * | ( - * | AB+C |
| D | ( - * | AB+CD |
| / | ( - / | AB+CD* |
| E | ( - / | AB+CD*E |
| ) | (empty) | AB+CD*E/- |
| * | * | AB+CD*E/- |
| ( | * ( | AB+CD*E/- |
| H | * ( | AB+CD*E/-H |
| - | * ( - | AB+CD*E/-H |
| I | * ( - | AB+CD*E/-HI |
| ) | * | AB+CD*E/-HI- |
| * | * | AB+CDE/-HI- |
| F | * | AB+CD*E/-HI-*F |
| + | + | AB+CD*E/-HI-F |
| G | + | AB+CD*E/-HI-FG |
| end | (empty) | AB+CD*E/-HI-FG+ |
Postfix:
Evaluation with . Scan left to right, pushing operands and applying each operator to the top two values.
| Symbol | Operation | Stack |
|---|---|---|
| A, B | push | 4, 2 |
| + | 6 | |
| C, D | push | 6, 4, 3 |
| * | 6, 12 | |
| E | push | 6, 12, 8 |
| / | 6, 1.5 | |
| - | 4.5 | |
| H, I | push | 4.5, 5, 1 |
| - | 4.5, 4 | |
| * | 18 | |
| F | push | 18, 2 |
| * | 36 | |
| G | push | 36, 3 |
| + | 39 |
Result of the expression .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 10 marks
What is double linked list? How does it differ from circular linked list? Write an algorithm or function to add a node at the beginning and end of double linked list.
Answer
Doubly linked list. A doubly linked list is a linked list in which every node has three fields: prev (address of the previous node), data, and next (address of the next node). It can therefore be traversed in both directions. The prev of the first node and the next of the last node are NULL.
Difference from a circular linked list
| Doubly linked list | Circular linked list |
|---|---|
Each node has two pointers, prev and next | Each node normally has one pointer, next (singly circular) |
| Traversal in both directions | Traversal in one direction (forward) |
First prev and last next are NULL | Last node points back to the first node; no NULL |
| Ends are identified by NULL | Ends are identified by returning to the start node |
| Deletion of a given node is easy (no need for predecessor search) | Need to traverse to find the predecessor |
(A list can also be both: a circular doubly linked list.)
Node and functions in C
struct node {
int data;
struct node *prev, *next;
};
struct node *head = NULL;
void insertBeginning(int x) {
struct node *n = (struct node *)malloc(sizeof(struct node));
n->data = x;
n->prev = NULL;
n->next = head;
if (head != NULL)
head->prev = n;
head = n;
}
void insertEnd(int x) {
struct node *n = (struct node *)malloc(sizeof(struct node));
n->data = x;
n->next = NULL;
if (head == NULL) {
n->prev = NULL;
head = n;
return;
}
struct node *t = head;
while (t->next != NULL)
t = t->next;
t->next = n;
n->prev = t;
}
Algorithm, add at beginning: create node N; set and ; if the list is not empty set ; set .
Algorithm, add at end: create node N with ; if the list is empty, set and ; otherwise move pointer T to the last node, set and .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2020 · 10 marks
What is heap? Differentiate between min heap and max heap. Sort the following data in ascending order by heap sort method:
2, 9, 3, 12, 15, 8, 11.
Answer
Heap. A heap is a complete binary tree (usually stored in an array) that satisfies the heap-order property between each parent and its children. For array index (1-based) the children are at and and the parent at .
| Min heap | Max heap |
|---|---|
| Every parent is its children | Every parent is its children |
| Root holds the minimum element | Root holds the maximum element |
| Used for priority queues with smallest first; gives descending order in heap sort | Used for priority queues with largest first; gives ascending order in heap sort |
Heap sort (ascending) uses a max heap: build the heap, then repeatedly swap the root with the last element, reduce the heap size by one and restore the heap.
Data: 2, 9, 3, 12, 15, 8, 11 (array positions 1 to 7).
Build max heap (heapify from position 3 down to 1):
- Position 3 (3) with children 8, 11: swap with 11, giving 2, 9, 11, 12, 15, 8, 3.
- Position 2 (9) with children 12, 15: swap with 15, giving 2, 15, 11, 12, 9, 8, 3.
- Position 1 (2) with children 15, 11: swap with 15, then 2 sinks below 12, giving 15, 12, 11, 2, 9, 8, 3.
Sorting phase (the part after | is the sorted portion):
| Step | Array after swap | Array after heapify |
|---|---|---|
| 1 | 3, 12, 11, 2, 9, 8 | 15 | 12, 9, 11, 2, 3, 8 | 15 |
| 2 | 8, 9, 11, 2, 3 | 12, 15 | 11, 9, 8, 2, 3 | 12, 15 |
| 3 | 3, 9, 8, 2 | 11, 12, 15 | 9, 3, 8, 2 | 11, 12, 15 |
| 4 | 2, 3, 8 | 9, 11, 12, 15 | 8, 3, 2 | 9, 11, 12, 15 |
| 5 | 2, 3 | 8, 9, 11, 12, 15 | 3, 2 | 8, 9, 11, 12, 15 |
| 6 | 2 | 3, 8, 9, 11, 12, 15 | 2 | 3, 8, 9, 11, 12, 15 |
Sorted result: 2, 3, 8, 9, 11, 12, 15.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
What is data structure? Explain its importance.
Answer
Data structure. A data structure is a particular way of organizing, storing and managing data in the memory of a computer so that it can be accessed and modified efficiently. It defines the data, the relationships among the data items, and the operations allowed on them. Examples: array, linked list, stack, queue, tree, graph, hash table.
Data structures are classified as primitive (int, char, float) and non-primitive; non-primitive ones are linear (array, list, stack, queue) or non-linear (tree, graph).
Importance
- Efficiency: the right structure reduces time and memory, for example searching a sorted array by binary search takes against for a linear scan.
- Organization of large data: helps to handle huge volumes of data (databases, file systems, search engines) in a systematic way.
- Reusability: a well-defined structure and its operations can be reused in many programs.
- Abstraction: users work with operations such as push, pop or insert without needing to know the internal implementation.
- Problem solving: many algorithms depend on a suitable structure, such as a stack for expression evaluation, a queue for scheduling, a graph for shortest routes, a tree for hierarchical data.
- Better program design: makes programs easier to understand, maintain and extend.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Write an algorithm to convert infix expression to postfix.
Answer
Algorithm: convert infix expression to postfix using a stack
Precedence (high to low): ^ (right associative), then * and /, then + and -. Operators of equal precedence associate left to right (except ^).
Input: infix expression (token list). Output: postfix expression .
- Create an empty stack and an empty output . Push
(onto and append)to the end of . - Read the next token of from left to right and repeat steps 3 to 6 until is empty.
- If is an operand, append it to .
- If is
(, push it onto . - If is an operator:
- while the top of is an operator whose precedence is higher than, or equal to, that of (for
^only strictly higher), pop it and append it to ; - push onto .
- while the top of is an operator whose precedence is higher than, or equal to, that of (for
- If is
):- pop operators from and append them to until
(is on top; - pop and discard
(.
- pop operators from and append them to until
- Exit; is the postfix expression.
Example. gives: A to output; + pushed; B to output; * has higher precedence than +, so it is pushed; C to output; at the end pop * then +. Postfix: .
C function sketch
int prec(char c){ return c=='^'?3 : (c=='*'||c=='/')?2 : (c=='+'||c=='-')?1 : 0; }
void infixToPostfix(char in[], char post[]) {
char st[100]; int top = -1, k = 0;
for (int i = 0; in[i] != '\0'; i++) {
char c = in[i];
if (isalnum(c)) post[k++] = c;
else if (c == '(') st[++top] = c;
else if (c == ')') {
while (top >= 0 && st[top] != '(') post[k++] = st[top--];
top--; /* discard '(' */
} else {
while (top >= 0 && st[top] != '(' &&
(prec(st[top]) > prec(c) ||
(prec(st[top]) == prec(c) && c != '^')))
post[k++] = st[top--];
st[++top] = c;
}
}
while (top >= 0) post[k++] = st[top--];
post[k] = '\0';
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 1 MCQ
Loading…
- 2021 · 5 marks
Write a recursive program to generate Fibonacci number up to nth terms.
Answer
The Fibonacci series is where
C program
#include <stdio.h>
int fib(int n) {
if (n == 0) return 0; /* base cases */
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
int main() {
int n, i;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci series: ");
for (i = 0; i < n; i++)
printf("%d ", fib(i));
return 0;
}
For the output is 0 1 1 2 3 5 8. The function calls itself with smaller arguments until it reaches a base case. This simple recursion takes exponential time, about , because sub-problems are recomputed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
What is insertion sort? Trace and sort the following data using insertion sort:
90, 57, 80, 10, 22, 21, 45, 9, 78
Answer
Insertion sort builds the sorted list one element at a time. The first element is regarded as sorted; each following element (the key) is compared with the elements of the sorted part on its left, larger elements are shifted one place right, and the key is inserted into its correct position. Worst and average time is , best case (already sorted) is ; it is stable and in place.
Trace: 90, 57, 80, 10, 22, 21, 45, 9, 78 (the part before | is sorted).
| Pass | Key | Array after pass |
|---|---|---|
| Start | 90 | 57, 80, 10, 22, 21, 45, 9, 78 | |
| 1 | 57 | 57, 90 | 80, 10, 22, 21, 45, 9, 78 |
| 2 | 80 | 57, 80, 90 | 10, 22, 21, 45, 9, 78 |
| 3 | 10 | 10, 57, 80, 90 | 22, 21, 45, 9, 78 |
| 4 | 22 | 10, 22, 57, 80, 90 | 21, 45, 9, 78 |
| 5 | 21 | 10, 21, 22, 57, 80, 90 | 45, 9, 78 |
| 6 | 45 | 10, 21, 22, 45, 57, 80, 90 | 9, 78 |
| 7 | 9 | 9, 10, 21, 22, 45, 57, 80, 90 | 78 |
| 8 | 78 | 9, 10, 21, 22, 45, 57, 78, 80, 90 |
Sorted: 9, 10, 21, 22, 45, 57, 78, 80, 90.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
What is hashing? Explain with example the collision resolution method open hashing.
Answer
Hashing is a technique to store and retrieve data in nearly constant time using a hash table. A hash function converts a key into an index of the table, and the record is stored at that index. For a table of size , a common hash function is
When two different keys give the same index, a collision occurs and must be resolved.
Open hashing (separate chaining). Each table slot holds a pointer to a linked list (chain). All keys that hash to the same index are inserted in the list of that slot, so the table never overflows.
Example. , , keys: 15, 25, 35, 42, 52, 9, 19.
| Index | Chain |
|---|---|
| 0, 1, 3, 4, 6, 7, 8 | empty |
| 2 | 42 → 52 |
| 5 | 15 → 25 → 35 |
| 9 | 9 → 19 |
Here 25 and 35 collide with 15 at index 5, 52 collides with 42 at index 2, and 19 collides with 9 at index 9; each is simply appended to the chain. Search for a key computes and scans only that chain. Average time is where is the load factor.
Advantages: simple, deletion is easy, table size is not a hard limit. Disadvantage: extra memory for pointers and poorer cache behaviour.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Write the difference between serial and parallel algorithm with example.
Answer
Serial (sequential) algorithm. Instructions are executed one after another on a single processor; only one operation is performed at any instant. Most traditional algorithms are of this type.
Parallel algorithm. The problem is divided into independent sub-problems that are executed simultaneously on multiple processors (or cores), and the partial results are then combined.
| Serial algorithm | Parallel algorithm |
|---|---|
| One processor executes one step at a time | Many processors execute steps at the same time |
| Time depends on the total number of operations | Time depends on the longest chain of dependent steps and on the number of processors |
| Simple to design, debug and analyse | More complex: needs decomposition, synchronization and communication |
| No communication overhead | Communication and synchronization overhead |
| Speed limited by one processor | Can give speed-up on large problems |
Example: sum of numbers.
- Serial:
sum = 0; for i in 1..n: sum = sum + a[i]takes additions one after another, time . - Parallel: with processors, add pairs simultaneously: step 1 gives partial sums, step 2 gives , and so on. For : step 1 gives 3, 7, 11, 15; step 2 gives 10, 26; step 3 gives 36. Only parallel steps are needed, so time is .
Merge sort is another example: the two halves can be sorted in parallel.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Write a program to implement basic operation in queue.
Answer
A queue is a linear data structure that follows First In First Out (FIFO). Insertion (enqueue) is at the rear and deletion (dequeue) is at the front. The basic operations are enqueue, dequeue, peek/display, isEmpty and isFull.
C program (array implementation)
#include <stdio.h>
#define MAX 5
int queue[MAX];
int front = -1, rear = -1;
int isEmpty() { return front == -1; }
int isFull() { return rear == MAX - 1; }
void enqueue(int x) {
if (isFull()) { printf("Queue overflow\n"); return; }
if (front == -1) front = 0;
queue[++rear] = x;
}
void dequeue() {
if (isEmpty()) { printf("Queue underflow\n"); return; }
printf("Deleted: %d\n", queue[front]);
if (front == rear) front = rear = -1; /* queue became empty */
else front++;
}
void display() {
if (isEmpty()) { printf("Queue is empty\n"); return; }
for (int i = front; i <= rear; i++)
printf("%d ", queue[i]);
printf("\n");
}
int main() {
int ch, x;
do {
printf("1.Enqueue 2.Dequeue 3.Display 4.Exit: ");
scanf("%d", &ch);
switch (ch) {
case 1: printf("Value: "); scanf("%d", &x); enqueue(x); break;
case 2: dequeue(); break;
case 3: display(); break;
}
} while (ch != 4);
return 0;
}
Each operation takes time. A weakness of this linear queue is that freed space at the front cannot be reused; a circular queue removes this problem.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
What is circular linked list? Write a function to delete the node from linked list.
Answer
Circular linked list. A circular linked list is a linked list in which the next pointer of the last node points back to the first node instead of NULL, so the list forms a ring. It can be singly or doubly linked. Any node can be a starting point, and traversal ends when we return to the start node. It is useful for round-robin scheduling and buffers.
Node and deletion functions (singly circular list)
struct node {
int data;
struct node *next;
};
struct node *head = NULL; /* points to first node */
/* delete the first node */
void deleteFirst() {
if (head == NULL) { printf("List empty\n"); return; }
struct node *t = head;
if (head->next == head) { /* only one node */
head = NULL;
} else {
struct node *last = head;
while (last->next != head) last = last->next;
head = head->next;
last->next = head;
}
free(t);
}
/* delete the last node */
void deleteLast() {
if (head == NULL) { printf("List empty\n"); return; }
if (head->next == head) { free(head); head = NULL; return; }
struct node *prev = head, *cur = head->next;
while (cur->next != head) { prev = cur; cur = cur->next; }
prev->next = head;
free(cur);
}
/* delete the node containing key */
void deleteNode(int key) {
if (head == NULL) { printf("List empty\n"); return; }
struct node *cur = head, *prev = NULL;
if (head->data == key) { deleteFirst(); return; }
do {
prev = cur;
cur = cur->next;
if (cur->data == key) {
prev->next = cur->next;
free(cur);
return;
}
} while (cur != head);
printf("Key not found\n");
}
Algorithm for deleting a given node
- If the list is empty, report underflow and stop.
- If the first node holds the key: if it is the only node, set ; otherwise find the last node, set and ; free the old first node.
- Otherwise traverse with two pointers (
prev,cur) untilcur->data = keyorcurreturns to head. - If found, set and free
cur; else report "not found".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
What do you mean by Huffman Algorithm? Explain with example. Construct the B tree of order 5 using following data: 20, 10, 26, 55, 80, 11, 9, 60, 67, 55, 22, 76, 56, 45, 34, 100, 150
Answer
Huffman algorithm. Huffman coding is a greedy algorithm for lossless data compression. It assigns shorter binary codes to characters that occur more often and longer codes to rarer ones. The codes are prefix codes (no code is the prefix of another), so a bit stream can be decoded unambiguously.
Algorithm
- Create a leaf node for every character with its frequency and place all nodes in a min priority queue.
- Remove the two nodes with the smallest frequencies, create a new internal node whose frequency is their sum, with these two as children, and insert it back.
- Repeat step 2 until only one node (the root) remains.
- Label left edges 0 and right edges 1; the path from the root to a leaf is that character's code.
Example. Frequencies: a = 5, b = 9, c = 12, d = 13, e = 16, f = 45.
- 5 + 9 = 14 (a, b)
- 12 + 13 = 25 (c, d)
- 14 + 16 = 30 (14, e)
- 25 + 30 = 55
- 45 + 55 = 100 (root; f left, 55 right)
| Character | Code | Frequency | Bits |
|---|---|---|---|
| f | 0 | 45 | 45 |
| c | 100 | 12 | 36 |
| d | 101 | 13 | 39 |
| a | 1100 | 5 | 20 |
| b | 1101 | 9 | 36 |
| e | 111 | 16 | 48 |
Total bits, against bits for fixed 3-bit codes.
B-tree of order 5. Order 5 means at most 5 children and 4 keys per node; every non-root node has at least 2 keys. When a node gets a fifth key it splits and the median key moves up. The key 55 appears twice in the data; a B-tree stores distinct keys, so the second 55 is ignored.
Insertion of 20, 10, 26, 55, 80, 11, 9, 60, 67, 22, 76, 56, 45, 34, 100, 150:
- 20, 10, 26, 55 give the node [10, 20, 26, 55].
- Insert 80: overflow [10, 20, 26, 55, 80]; median 26 goes up. Root [26] with children [10, 20] and [55, 80].
- Insert 11, 9: left child becomes [9, 10, 11, 20]. Insert 60, 67: right child becomes [55, 60, 67, 80].
- Insert 22: left child overflows [9, 10, 11, 20, 22]; median 11 goes up. Root [11, 26]; children [9, 10], [20, 22], [55, 60, 67, 80].
- Insert 76: right child overflows [55, 60, 67, 76, 80]; median 67 goes up. Root [11, 26, 67]; children [9, 10], [20, 22], [55, 60], [76, 80].
- Insert 56: [55, 56, 60]. Insert 45: [45, 55, 56, 60].
- Insert 34: that child overflows [34, 45, 55, 56, 60]; median 55 goes up. Root [11, 26, 55, 67].
- Insert 100 and 150: last child becomes [76, 80, 100, 150].
Final B-tree
[ 11 | 26 | 55 | 67 ]
/ | | | \
[9,10] [20,22] [34,45] [56,60] [76,80,100,150]
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
What do you mean by MST? Explain Kruskal's algorithm with example.
Answer
Minimum spanning tree (MST). A spanning tree of a connected, undirected graph is a subgraph that contains all vertices, is connected and has no cycles (it has exactly edges). In a weighted graph, the spanning tree whose total edge weight is the smallest is the minimum spanning tree. Applications: laying cables, pipelines or roads at least cost, network design.
Kruskal's algorithm finds the MST by a greedy strategy.
- Sort all edges in non-decreasing order of weight.
- Make each vertex a separate set (tree).
- For each edge in sorted order: if and belong to different sets, add the edge to the MST and union the two sets; otherwise skip it because it would form a cycle.
- Stop when the MST has edges.
KRUSKAL(G):
T = empty
for each vertex v: MAKE-SET(v)
sort edges by weight
for each edge (u, v) in order:
if FIND(u) != FIND(v):
T = T + {(u, v)}
UNION(u, v)
return T
Time complexity is (sorting dominates); the disjoint-set operations are almost constant.
Example. Vertices A to F; 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.
| Sorted edge | Weight | Action | Components after |
|---|---|---|---|
| B-C | 1 | add | {B,C} |
| A-C | 2 | add | {A,B,C} |
| D-E | 2 | add | {D,E} |
| E-F | 3 | add | {D,E,F} |
| A-B | 4 | skip (cycle A-B-C) | |
| B-D | 5 | add | {A,B,C,D,E,F} |
The remaining edges (D-F 6, C-D 8, C-E 10) are not needed. MST edges: B-C, A-C, D-E, E-F, B-D.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What is abstract data type? Convert a$b*c-d+e/f/(g+h) into postfix expression using stack.
Answer
Abstract data type (ADT). An ADT is a mathematical model of a data structure that specifies the type of data stored and the operations that may be performed on it, together with what those operations do, but not how they are implemented. The user sees only the interface; the implementation (array or linked list, for example) is hidden. A stack ADT, for instance, is defined by push, pop, peek, isEmpty and isFull following the LIFO rule, whether it is built on an array or a linked list. Other ADTs: queue, list, tree, graph.
Conversion of to postfix. Precedence: $ (exponent, right associative) highest, then * and /, then + and -; equal precedence is left to right.
| Symbol | Stack | Output |
|---|---|---|
| a | a | |
| $ | $ | a |
| b | $ | ab |
| * | * (pop $) | ab$ |
| c | * | ab$c |
| - | - (pop *) | ab$c* |
| d | - | ab$c*d |
| + | + (pop -) | ab$c*d- |
| e | + | ab$c*d-e |
| / | + / | ab$c*d-e |
| f | + / | ab$c*d-ef |
| / | + / (pop first /) | ab$c*d-ef/ |
| ( | + / ( | ab$c*d-ef/ |
| g | + / ( | ab$c*d-ef/g |
| + | + / ( + | ab$c*d-ef/g |
| h | + / ( + | ab$c*d-ef/gh |
| ) | + / | ab$c*d-ef/gh+ |
| end | pop all | ab$c*d-ef/gh+/+ |
Postfix expression:
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What is linked list? Describe types of linked list. Write an algorithm to insert and delete node from beginning of doubly linked list.
Answer
Linked list. A linked list is a linear collection of elements called nodes, where each node contains data and a link (pointer) to the next node. Nodes need not be in contiguous memory, so the size can grow or shrink at run time and insertion/deletion needs no shifting of elements.
Types of linked list
- Singly linked list: each node has data and one
nextpointer; traversal only forward; the last node points to NULL. - Doubly linked list: each node has
prev, data andnext; traversal in both directions. - Circular linked list: the last node points back to the first (singly or doubly), so there is no NULL.
Node structure
struct node { int data; struct node *prev, *next; };
struct node *head = NULL;
Insert at beginning of a doubly linked list
- Create a new node N and set .
- Set and .
- If , set .
- Set .
Delete from beginning
- If , print "underflow" and stop.
- Set .
- Set .
- If , set .
- Free .
void insertBegin(int x) {
struct node *n = malloc(sizeof(struct node));
n->data = x; n->prev = NULL; n->next = head;
if (head) head->prev = n;
head = n;
}
void deleteBegin() {
if (head == NULL) { printf("Underflow\n"); return; }
struct node *t = head;
head = head->next;
if (head) head->prev = NULL;
free(t);
}
Both operations take time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
Describe Prim's algorithm to solve MST problem with suitable illustration.
Answer
Prim's algorithm finds a minimum spanning tree (MST) of a connected, weighted, undirected graph by growing a single tree from a start vertex. At each step it adds the cheapest edge that connects a vertex already in the tree to a vertex outside it.
Steps
- Choose any start vertex and put it in the tree set .
- Among all edges with one end in and the other outside , pick the edge of minimum weight.
- Add that edge and its new vertex to the tree.
- Repeat until all vertices are in the tree ( edges).
Time complexity is with an adjacency matrix and with a binary heap.
Illustration. Vertices A to F; 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. Start at A.
| Step | Tree vertices | Candidate edges leaving the tree | Chosen edge |
|---|---|---|---|
| 1 | {A} | A-B 4, A-C 2 | A-C (2) |
| 2 | {A,C} | A-B 4, C-B 1, C-D 8, C-E 10 | C-B (1) |
| 3 | {A,B,C} | B-D 5, C-D 8, C-E 10 | B-D (5) |
| 4 | {A,B,C,D} | D-E 2, D-F 6, C-E 10 | D-E (2) |
| 5 | {A,B,C,D,E} | E-F 3, D-F 6 | E-F (3) |
All six vertices are now included. MST edges: A-C, C-B, B-D, D-E, E-F.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What is the limitation of linear queue over circular queue? Write an algorithm to insert and delete node in circular queue.
Answer
Limitation of a linear queue over a circular queue. In a linear (array) queue, rear only moves forward and front only moves forward on deletion. After some deletions the positions at the beginning of the array are empty but can never be reused, because insertion is allowed only when is not reached. The queue reports "overflow" even though free cells exist, so memory is wasted (or all elements must be shifted at cost ). A circular queue treats the array as a ring, so rear wraps around to index 0 and the freed cells are reused.
Circular queue algorithms (array of size MAX; initially )
Insert (enqueue)
- If , print "overflow" and stop.
- If , set ; otherwise set .
- Set .
Delete (dequeue)
- If , print "underflow" and stop.
- Set .
- If , set (queue becomes empty); otherwise set .
- Return .
void enqueue(int x) {
if ((rear + 1) % MAX == front) { printf("Overflow\n"); return; }
if (front == -1) front = rear = 0;
else rear = (rear + 1) % MAX;
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) % MAX;
return x;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
Define divide and conquer algorithm. What is binary search? Write an algorithm to search an item using binary search with suitable illustration.
Answer
Divide and conquer is an algorithm design strategy that solves a problem in three steps:
- Divide the problem into smaller sub-problems of the same type.
- Conquer the sub-problems by solving them (recursively; solve directly if small enough).
- Combine the sub-solutions into the solution of the original problem.
Examples: binary search, merge sort, quick sort. Its running time typically follows .
Binary search searches a sorted array by comparing the key with the middle element and discarding half of the array each time. In the divide-and-conquer view: divide at the middle, conquer one half only, nothing to combine. Time is .
Algorithm
- Set , .
- While : compute .
- If , return .
- If , set ; else set .
- If the loop ends, return (not found).
Illustration. (indices 0 to 8), key .
| Step | low | high | mid | A[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 27 | , so |
| 2 | 5 | 8 | 6 | 42 | equal, found |
The key is found at index 6 in two comparisons. For key : mid = 4 (27) gives ; mid = 1 (8) gives ; mid = 2 (14) gives ; now , so the key is not present.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What is minimax algorithm? Create Huffman Tree and calculate Huffman code for the following characters along with their frequencies using Huffman algorithm.
Characters : A, E, I, O, U, S, T
Frequencies: 10, 15, 12, 3, 4, 13, 1
Answer
Minimax algorithm. Minimax is a recursive decision (backtracking) algorithm used in two-player zero-sum games such as tic-tac-toe or chess. One player, MAX, tries to maximize the score and the opponent, MIN, tries to minimize it. The game tree is built to some depth; leaf positions get a utility value; then values are propagated upward: a MAX node takes the largest value of its children and a MIN node takes the smallest. At the root, MAX chooses the move leading to the best guaranteed value assuming the opponent plays optimally. Time is for branching factor and depth ; alpha-beta pruning can cut the search.
Huffman tree. Frequencies: A 10, E 15, I 12, O 3, U 4, S 13, T 1 (total 58).
- Merge the two smallest, T (1) and O (3), into node N1 = 4.
- Smallest now N1 (4) and U (4): merge into N2 = 8.
- Smallest: N2 (8) and A (10): merge into N3 = 18.
- Smallest: I (12) and S (13): merge into N4 = 25.
- Smallest: E (15) and N3 (18): merge into N5 = 33.
- Merge N4 (25) and N5 (33) into the root = 58.
(58)
0 / \ 1
(25) (33)
0/ \1 0/ \1
I S E (18)
0/ \1
(8) A
0/ \1
(4) U
0/ \1
T O
Huffman codes (left edge 0, right edge 1)
| Character | Frequency | Code | Bits (freq × length) |
|---|---|---|---|
| I | 12 | 00 | 24 |
| S | 13 | 01 | 26 |
| E | 15 | 10 | 30 |
| A | 10 | 111 | 30 |
| U | 4 | 1101 | 16 |
| T | 1 | 11000 | 5 |
| O | 3 | 11001 | 15 |
Total bits, compared with bits for a fixed 3-bit code.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
What is stack? List the application of the stack. Write an algorithm to perform PUSH and POP operation in stack. Describe linked list implementation of stack operations.
Answer
Stack. A stack is a linear data structure in which insertion (PUSH) and deletion (POP) are done at one end only, the top, following Last In First Out (LIFO).
Applications: expression conversion and evaluation (infix, postfix, prefix); recursion and function-call management; parenthesis matching; undo/redo and browser back; reversing data; depth first search and backtracking.
Array implementation algorithms (stack of size , initially)
PUSH(x)
- If , print "stack overflow" and stop.
- Set .
- Set .
POP()
- If , print "stack underflow" and stop.
- Set .
- Set .
- Return .
Linked list implementation. The stack is a singly linked list in which the head (top) pointer is the top of the stack. Push inserts a node at the beginning and pop deletes the first node, so both are and there is no fixed size limit (overflow happens only when memory is exhausted).
struct node { int data; struct node *next; };
struct node *top = NULL;
void push(int x) {
struct node *n = malloc(sizeof(struct node));
if (n == NULL) { printf("Overflow\n"); return; }
n->data = x;
n->next = top; /* new node points to old top */
top = n; /* new node becomes top */
}
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;
}
Push: create node, set its next to top, set top to the new node. Pop: if top is NULL report underflow; else save top, move top to top->next, free the saved node and return its data. The stack is empty when top == NULL.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
What is external sorting? Explain heap sort algorithm and trace it to sort the data:
82, 90, 10, 12, 15, 77, 55, 23, 25, 32
Answer
External sorting. External sorting is used when the data to be sorted is too large to fit in main memory and resides on external storage (disk or tape). The data is sorted in chunks that fit in memory (runs), the sorted runs are written to disk, and then the runs are merged. The standard method is external merge sort; the main cost is the number of disk accesses.
Heap sort. Heap sort uses a binary max heap (a complete binary tree where every parent is its children).
- Build a max heap from the array (heapify nodes from down to 1).
- Repeat times: swap the root (largest) with the last element of the heap, reduce the heap size by 1, and heapify the root to restore the heap.
Time is in all cases, space , not stable.
Trace for 82, 90, 10, 12, 15, 77, 55, 23, 25, 32 (positions 1 to 10).
Building the max heap
- Position 5 (15) with child 32: swap, giving 82, 90, 10, 12, 32, 77, 55, 23, 25, 15.
- Position 4 (12) with children 23, 25: swap with 25, giving 82, 90, 10, 25, 32, 77, 55, 23, 12, 15.
- Position 3 (10) with children 77, 55: swap with 77, giving 82, 90, 77, 25, 32, 10, 55, 23, 12, 15.
- Position 2 (90): already larger than its children.
- Position 1 (82) with children 90, 77: swap with 90.
Max heap: 90, 82, 77, 25, 32, 10, 55, 23, 12, 15
Sorting phase (after | is the sorted part)
| Step | After swapping root with last | After heapify |
|---|---|---|
| 1 | 15, 82, 77, 25, 32, 10, 55, 23, 12 | 90 | 82, 32, 77, 25, 15, 10, 55, 23, 12 | 90 |
| 2 | 12, 32, 77, 25, 15, 10, 55, 23 | 82, 90 | 77, 32, 55, 25, 15, 10, 12, 23 | 82, 90 |
| 3 | 23, 32, 55, 25, 15, 10, 12 | 77, 82, 90 | 55, 32, 23, 25, 15, 10, 12 | 77, 82, 90 |
| 4 | 12, 32, 23, 25, 15, 10 | 55, 77, 82, 90 | 32, 25, 23, 12, 15, 10 | 55, 77, 82, 90 |
| 5 | 10, 25, 23, 12, 15 | 32, 55, 77, 82, 90 | 25, 15, 23, 12, 10 | 32, 55, 77, 82, 90 |
| 6 | 10, 15, 23, 12 | 25, 32, 55, 77, 82, 90 | 23, 15, 10, 12 | 25, 32, 55, 77, 82, 90 |
| 7 | 12, 15, 10 | 23, 25, 32, 55, 77, 82, 90 | 15, 12, 10 | 23, 25, 32, 55, 77, 82, 90 |
| 8 | 10, 12 | 15, 23, 25, 32, 55, 77, 82, 90 | 12, 10 | 15, 23, 25, 32, 55, 77, 82, 90 |
| 9 | 10 | 12, 15, 23, 25, 32, 55, 77, 82, 90 | 10 |
Sorted: 10, 12, 15, 23, 25, 32, 55, 77, 82, 90.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
Differentiate between BST and AVL tree. Given the following AVL Tree: Draw the resulting BST after 5 is removed, but before any rebalancing takes place. Label each node in the resulting tree with its balance factor. Replace a node with both children using an appropriate value from the node's left child.
Answer
BST vs AVL tree
| Binary search tree (BST) | AVL tree |
|---|---|
| Left subtree keys < node < right subtree keys | A BST that is also height balanced |
| No balance condition; may become skewed (like a linked list) | Balance factor of every node is , or |
| Search, insert, delete are in the worst case | Always |
| No rotations | Rotations (LL, RR, LR, RL) restore balance after insertion/deletion |
| No extra information stored | Stores height or balance factor in each node |
The balance factor is .
Deleting a node from an AVL tree. The node is first removed as in an ordinary BST, with no rebalancing yet:
- a leaf is simply removed;
- a node with one child is replaced by that child;
- a node with two children is replaced by a value from its left child's subtree, the largest value there (the in-order predecessor), and the node that held that value is removed.
Then the balance factors are recomputed from the changed place up to the root. A node with would need a rotation.
Worked example. Consider the AVL tree
10
/ \
5 15
/ \
2 7
Removing 5 (two children): the largest value in its left child's subtree (just node 2) is 2, so 2 replaces 5 and the old leaf 2 is removed. The BST before rebalancing:
10
/ \
2 15
\
7
Balance factors (leaf height 1, empty subtree height 0):
| Node | Left height | Right height | BF |
|---|---|---|---|
| 7 | 0 | 0 | 0 |
| 2 | 0 | 1 | |
| 15 | 0 | 0 | 0 |
| 10 | 2 | 1 |
All balance factors lie in , so this tree is still an AVL tree and no rotation is required. If some node had reached , a single or double rotation would then be applied.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Define stack. Why stack is considered as an ADT? List any four applications of stack.
Answer
Stack. A stack is a linear data structure in which insertion (push) and deletion (pop) take place at one end only, called the top. The element inserted last is removed first, so it follows the LIFO (Last In First Out) principle.
Why a stack is an ADT. An Abstract Data Type is defined by the data it holds and the operations allowed on it, not by how it is implemented. A stack is specified entirely by its operations: push(x), pop(), peek(), isEmpty() and isFull(), together with the LIFO rule. The user only needs these operations; the stack may be implemented with an array or a linked list without changing the way it is used. Because the interface is separated from the implementation, the stack is an ADT.
Applications of stack
- Conversion of infix expressions to postfix or prefix, and evaluation of postfix expressions.
- Function call management and recursion (the call stack stores return addresses and local variables).
- Undo/redo operations in editors and browser back-history.
- Checking balanced parentheses and syntax parsing in compilers.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Evaluate the following postfix expression using the stack: 4 5 + 7 3 - 2 + *
Answer
Postfix expression: 4 5 + 7 3 - 2 + *
Scan left to right. Push operands; on an operator pop the top two values (second popped is the left operand), apply the operator and push the result.
| Symbol | Action | Stack (bottom to top) |
|---|---|---|
| 4 | push | 4 |
| 5 | push | 4, 5 |
| + | 4 + 5 = 9 | 9 |
| 7 | push | 9, 7 |
| 3 | push | 9, 7, 3 |
| - | 7 - 3 = 4 | 9, 4 |
| 2 | push | 9, 4, 2 |
| + | 4 + 2 = 6 | 9, 6 |
| * | 9 * 6 = 54 | 54 |
Result = 54.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is tower of Hanoi problem? How recursion can be used of Hanoi problem?
Answer
Tower of Hanoi. There are three pegs (source A, auxiliary B, destination C) and disks of different sizes stacked on A with the largest at the bottom. The task is to move all disks to C under these rules: only one disk is moved at a time, only the top disk of a peg can be moved, and a larger disk may never be placed on a smaller one.
Recursive solution. To move disks from A to C using B:
- Move the top disks from A to B (using C as auxiliary).
- Move the largest disk from A to C.
- Move the disks from B to C (using A as auxiliary).
The problem reduces to the same problem with disks, with base case (move the disk directly).
void hanoi(int n, char from, char to, char aux) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
hanoi(n - 1, from, aux, to);
printf("Move disk %d from %c to %c\n", n, from, to);
hanoi(n - 1, aux, to, from);
}
The number of moves satisfies , giving . For there are 7 moves.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Define hashing. Explain how to resolve collisions during hashing using open addressing.
Answer
Hashing. Hashing is a technique that maps a key to a position in a table (hash table) using a hash function , so that searching, insertion and deletion take time on average. A common function is , where is the table size.
Collision. A collision occurs when two different keys give the same index, .
Open addressing. All keys are stored in the table itself. When the home slot is occupied, other slots are examined in a fixed probe sequence until an empty one is found: for
- Linear probing: . Check the next slots one by one. It is simple but causes primary clustering.
- Quadratic probing: . Probes slots at distance 1, 4, 9, ... which reduces primary clustering (but gives secondary clustering).
- Double hashing: , where is a second hash function (for example ). The step size depends on the key, which spreads keys well.
Example (linear probing, ). Insert 25, 35, 45: goes to slot 5; is occupied so it goes to slot 6; finds 5 and 6 occupied and goes to slot 7.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is binary search? Trace the algorithm of binary search to search a key 12 in the data: 11, 19, 5, 2, 7, 21, 8, 21, 12
Answer
Binary search is a searching technique for a sorted array. It compares the key with the middle element; if they are equal the search ends, if the key is smaller the search continues in the left half, otherwise in the right half. The search range is halved each step, so the time complexity is .
Trace. The data is not sorted, so sort it first:
2, 5, 7, 8, 11, 12, 19, 21, 21 (indices 0 to 8). Key = 12.
| Step | low | high | mid = (low+high)/2 | A[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 11 | 12 > 11, low = 5 |
| 2 | 5 | 8 | 6 | 19 | 12 < 19, high = 5 |
| 3 | 5 | 5 | 5 | 12 | found |
The key 12 is found at index 5 of the sorted array (6th position) after 3 comparisons.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is big-oh notation? Explain about divide and conquer strategy with example.
Answer
Big-oh notation. Big-oh gives an asymptotic upper bound on the growth of an algorithm's running time. if there exist positive constants and such that
For example, since for . It describes the worst-case growth and ignores constants and lower-order terms.
Divide and conquer. A problem is solved by three steps:
- Divide the problem into smaller sub-problems of the same type.
- Conquer by solving the sub-problems recursively (directly when small enough).
- Combine the sub-solutions into the solution of the original problem.
Example: merge sort. Divide the array into two halves, sort each half recursively, then merge the two sorted halves. For 38, 27, 43, 3: split into (38, 27) and (43, 3), then into single elements; merge to (27, 38) and (3, 43); merge to 3, 27, 38, 43. The recurrence is
Other examples are binary search and quick sort.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What are the depth and degree of a node in a tree? Perform pre-order, in-order and post-order traversal of the following tree:
Answer
Depth of a node: the number of edges on the path from the root to that node (the root has depth 0). The depth of the tree is the maximum depth of any node.
Degree of a node: the number of children (sub-trees) of that node. A leaf has degree 0. The degree of a tree is the maximum degree of its nodes.
Traversals. The tree figure is not reproduced here, so the traversals are shown on this tree:
A
/ \
B C
/ \ \
D E F
Here the depth of A is 0, B and C are 1, and D, E, F are 2; the degree of A and B is 2, of C is 1 and of D, E, F is 0.
- Pre-order (Root, Left, Right): A, B, D, E, C, F
- In-order (Left, Root, Right): D, B, E, A, C, F
- Post-order (Left, Right, Root): D, E, B, F, C, A
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
How dynamic implementation of the queue can be done? Explain with algorithm. Also explain how insertion and deletion of a node can be done at the end of a singly linked list with algorithm.
Answer
Dynamic implementation of a queue. A queue can be implemented with a singly linked list, so its size is not fixed. Two pointers are kept: front (the first node, where deletion happens) and rear (the last node, where insertion happens).
struct node { int data; struct node *next; };
struct node *front = NULL, *rear = NULL;
Enqueue
- Create a new node and set its data;
next = NULL. - If the queue is empty (
front == NULL), setfront = rear = new. - Otherwise set
rear->next = newandrear = new.
Dequeue
- If
front == NULL, report underflow and stop. - Set
temp = front, read its data, and setfront = front->next. - If
frontbecomesNULL, setrear = NULL. - Free
temp.
Both operations take time.
Insertion at the end of a singly linked list (head pointer head)
- Create node
newwith data andnew->next = NULL. - If
head == NULL, sethead = newand stop. - Set
temp = head; whiletemp->next != NULL, movetemp = temp->next. - Set
temp->next = new.
Deletion at the end
- If
head == NULL, report underflow. - If
head->next == NULL(one node), freeheadand sethead = NULL. - Otherwise set
temp = head; whiletemp->next->next != NULL, movetemp = temp->next. - Free
temp->nextand settemp->next = NULL.
Both operations need traversal of the list, so each takes time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
Define complete binary tree and skewed tree. Write a function to implement heap sort and sort the following data using heap sort: 12, 9, 1, 13, 16, 24, 21, 5
Answer
Complete binary tree. A binary tree in which every level is completely filled except possibly the last, and the nodes of the last level are filled from left to right. A binary tree with nodes stored in an array has children of node at and (0-based).
Skewed tree. A binary tree in which every node has only one child, so it behaves like a linked list. It is left-skewed if all children are left children and right-skewed if all are right children. Its height is .
Heap sort function (max-heap)
void heapify(int a[], int n, int i) {
int largest = i, l = 2 * i + 1, r = 2 * i + 2;
if (l < n && a[l] > a[largest]) largest = l;
if (r < n && a[r] > a[largest]) largest = r;
if (largest != i) {
int t = a[i]; a[i] = a[largest]; a[largest] = t;
heapify(a, n, largest);
}
}
void heapSort(int a[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) /* build max-heap */
heapify(a, n, i);
for (int i = n - 1; i > 0; i--) {
int t = a[0]; a[0] = a[i]; a[i] = t; /* move max to end */
heapify(a, i, 0);
}
}
Sorting 12, 9, 1, 13, 16, 24, 21, 5
Build the max-heap (heapify from index 3 down to 0):
- Index 3 (13): child 5, no change.
- Index 2 (1): swap with 24: 12, 9, 24, 13, 16, 1, 21, 5
- Index 1 (9): swap with 16: 12, 16, 24, 13, 9, 1, 21, 5
- Index 0 (12): swap with 24, then with 21: 24, 16, 21, 13, 9, 1, 12, 5
Extract the maximum repeatedly (the part after | is sorted):
| Step | Array after swap and heapify |
|---|---|
| 1 | 21, 16, 12, 13, 9, 1, 5 | 24 |
| 2 | 16, 13, 12, 5, 9, 1 | 21, 24 |
| 3 | 13, 9, 12, 5, 1 | 16, 21, 24 |
| 4 | 12, 9, 1, 5 | 13, 16, 21, 24 |
| 5 | 9, 5, 1 | 12, 13, 16, 21, 24 |
| 6 | 5, 1 | 9, 12, 13, 16, 21, 24 |
| 7 | 1 | 5, 9, 12, 13, 16, 21, 24 |
Sorted: 1, 5, 9, 12, 13, 16, 21, 24. Time complexity is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
How breadth first traversal and depth first traversal can be used for traversing a graph? Explain with example. Use Dijkstra's algorithm to find the shortest path from node A to all other nodes for the following graph.
Answer
Graph traversal visits every vertex reachable from a start vertex exactly once.
Breadth First Traversal (BFS) uses a queue and visits vertices level by level.
- Mark the start vertex visited and enqueue it.
- Dequeue a vertex, visit it, and enqueue all its unvisited neighbours (marking them visited).
- Repeat until the queue is empty.
Depth First Traversal (DFS) uses a stack (or recursion) and goes as deep as possible before backtracking.
- Push the start vertex and mark it visited.
- Visit an unvisited neighbour of the top vertex and push it; if none exists, pop the top.
- Repeat until the stack is empty.
Example. Graph with edges A-B, A-C, B-D, C-D, D-E, start at A (neighbours in alphabetical order):
- BFS: queue A; visit A, add B, C; visit B, add D; visit C; visit D, add E; visit E. Order: A, B, C, D, E.
- DFS: A, then B, then D (from B), then C (unvisited neighbour of D), back to D, then E. Order: A, B, D, C, E.
Both take time with adjacency lists.
Dijkstra's algorithm. The graph in the question is not reproduced, so the method is shown on this graph with weights: A-B = 4, A-C = 1, C-B = 2, B-D = 1, C-D = 5, B-E = 6, D-E = 3.
Set and all others . Repeatedly pick the unvisited vertex with the smallest distance, fix it, and relax its edges: if then .
| Selected | A | B | C | D | E |
|---|---|---|---|---|---|
| start | 0 | ∞ | ∞ | ∞ | ∞ |
| A (0) | 0 | 4 | 1 | ∞ | ∞ |
| C (1) | 0 | 3 | 1 | 6 | ∞ |
| B (3) | 0 | 3 | 1 | 4 | 9 |
| D (4) | 0 | 3 | 1 | 4 | 7 |
| E (7) | 0 | 3 | 1 | 4 | 7 |
Shortest distances from A: B = 3 (A-C-B), C = 1 (A-C), D = 4 (A-C-B-D), E = 7 (A-C-B-D-E).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Differentiate between stack and queue. What are the general applications of a stack?
Answer
Difference between stack and queue
| Stack | Queue |
|---|---|
| Follows LIFO (last in, first out). | Follows FIFO (first in, first out). |
| Insertion and deletion at one end (top). | Insertion at the rear, deletion at the front. |
One pointer (top). | Two pointers (front and rear). |
| Operations: push, pop, peek. | Operations: enqueue, dequeue. |
| Example: stack of plates, undo. | Example: ticket line, print queue. |
General applications of a stack
- Expression conversion (infix to postfix/prefix) and postfix evaluation.
- Function calls and recursion (the call stack).
- Parenthesis matching and syntax checking in compilers.
- Undo/redo in editors, browser back button, and depth-first graph traversal.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is a linked list? How doubly linked list is different from circular linked list? Explain with example.
Answer
Linked list. A linked list is a linear data structure made of nodes, where each node holds data and a pointer to the next node. Nodes are allocated dynamically and need not be contiguous in memory, so the size can grow or shrink at run time. The first node is pointed to by head, and the last node's pointer is NULL.
Doubly linked list. Each node has two pointers, prev and next, so it can be traversed in both directions. The prev of the first node and the next of the last node are NULL.
NULL <- [10] <-> [20] <-> [30] -> NULL
Circular linked list. The last node points back to the first node instead of NULL, so there is no end and any node can be reached from any other. It can be singly or doubly linked.
[10] -> [20] -> [30] -> (back to 10)
Differences
| Doubly linked list | Circular linked list |
|---|---|
Two pointers per node (prev, next). | Usually one pointer per node (next). |
Ends in NULL at both ends. | No NULL; last node links to the first. |
| Traversal in both directions. | Traversal in one direction, repeatedly around the loop. |
| Deleting a given node is easy. | Useful for round-robin scheduling. |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is recursion and recursive function? Write a recursive function to compute Fibonacci number.
Answer
Recursion is a technique in which a function solves a problem by calling itself on smaller instances of the same problem. A recursive function is a function that calls itself; it must have a base case that stops the recursion and a recursive case that moves towards the base case.
Fibonacci numbers. , , for .
#include <stdio.h>
int fib(int n) {
if (n == 0) return 0; /* base case */
if (n == 1) return 1; /* base case */
return fib(n - 1) + fib(n - 2);
}
int main() {
int n = 7;
printf("fib(%d) = %d\n", n, fib(n)); /* prints 13 */
return 0;
}
For : . This simple version takes exponential time, .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
How does collision occur during hashing? Explain any two hashing functions.
Answer
Collision. A hash function maps a large set of keys to a small table of slots. Since there are more possible keys than slots, two different keys can map to the same index, . This is a collision. For example, with , the keys 25 and 35 both map to index 5.
Two hash functions
- Division method: . It is fast; is best chosen as a prime not close to a power of 2. Example: , .
- Mid-square method: square the key and take the middle digits as the index. Example: , ; taking the middle three digits gives , so (mod the table size if required).
- Folding method (alternative): split the key into equal parts and add them. Example: gives ; drop the carry or take it modulo the table size.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is an AVL tree? Create an AVL tree from the following data:
18, 12, 14, 8, 5, 25, 31, 24, 27
Answer
AVL tree. An AVL tree is a self-balancing binary search tree in which, for every node, the heights of the left and right sub-trees differ by at most one. The balance factor is . When an insertion makes a node's , rotations (LL, RR, LR, RL) restore balance.
Construction from 18, 12, 14, 8, 5, 25, 31, 24, 27
- Insert 18, then 12 (left of 18).
- Insert 14 (right of 12): node 18 is unbalanced (left-right case). LR rotation makes 14 the root with children 12 and 18.
- Insert 8 (left of 12), then 5 (left of 8): node 12 is unbalanced (left-left case). Right rotation at 12 gives sub-tree 8 with children 5 and 12. Tree: 14 with left 8 (5, 12) and right 18.
- Insert 25 (right of 18), then 31 (right of 25): node 18 is unbalanced (right-right case). Left rotation at 18 gives sub-tree 25 with children 18 and 31.
- Insert 24: goes to the right of 18; all nodes stay balanced.
- Insert 27: goes to the left of 31; all nodes stay balanced.
Final AVL tree
14
/ \
8 25
/ \ / \
5 12 18 31
\ /
24 27
Both sub-trees of the root have height 3, so the tree is balanced.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What are deterministic and non-deterministic algorithms? Explain the use of Big Oh notation to measure the complexity of an algorithm with an example.
Answer
Deterministic algorithm. Every step has exactly one possible next step, so for the same input it always follows the same sequence of operations and gives the same output. Examples: binary search, merge sort.
Non-deterministic algorithm. At some steps it may choose among several possible next steps (it can "guess" the right one), so different runs may follow different paths. It is a theoretical model used for problems in the class NP; it is assumed to always make the correct choice. Examples: guessing a solution to the travelling salesman or satisfiability problem and then verifying it in polynomial time.
Big Oh notation. The complexity of an algorithm is measured as a function of input size . means for some constants and all . It gives an upper bound (worst case) and ignores constants and lower-order terms.
Example.
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
sum++;
The statement sum++ runs times. If the whole code costs , then for , , so . In comparison, linear search is and binary search is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Implement the quick sort to sort the following data items:
12, 1, 14, 7, 2, 10, 4, 7, 22, 6, 15
Answer
Quick sort is a divide and conquer algorithm. A pivot is chosen, the array is partitioned so that smaller elements are on its left and larger on its right, and both parts are sorted recursively. Average time is ; worst case .
int partition(int a[], int low, int high) {
int pivot = a[high], i = low - 1, t;
for (int j = low; j < high; j++)
if (a[j] <= pivot) { i++; t = a[i]; a[i] = a[j]; a[j] = t; }
t = a[i + 1]; a[i + 1] = a[high]; a[high] = t;
return i + 1;
}
void quickSort(int a[], int low, int high) {
if (low < high) {
int p = partition(a, low, high);
quickSort(a, low, p - 1);
quickSort(a, p + 1, high);
}
}
Trace (last element as pivot) on 12, 1, 14, 7, 2, 10, 4, 7, 22, 6, 15:
- Pivot 15: result 12, 1, 14, 7, 2, 10, 4, 7, 6, 15, 22. Sort left part (12, 1, 14, 7, 2, 10, 4, 7, 6); right part (22) is done.
- Pivot 6: result 1, 2, 4, 6, 12, 10, 14, 7, 7. Left part (1, 2, 4) is already sorted.
- On (12, 10, 14, 7, 7) with pivot 7: result 7, 7, 14, 12, 10.
- On (14, 12, 10) with pivot 10: result 10, 12, 14, and then (12, 14) is sorted.
Sorted output: 1, 2, 4, 6, 7, 7, 10, 12, 14, 15, 22.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
What are the differences between linear queue and circular queue? Write an algorithm to enqueue and dequeue data elements in a circular queue.
Answer
Linear queue vs circular queue
| Linear queue | Circular queue |
|---|---|
rear moves only forward; the array end is a hard limit. | The last position is connected to the first, so indices wrap around. |
| Space freed by dequeue at the front cannot be reused, so "queue full" can be reported while empty slots exist. | Freed space is reused, so memory is used efficiently. |
Full when rear == MAX - 1. | Full when (rear + 1) % MAX == front. |
Insertion: rear = rear + 1. | Insertion: rear = (rear + 1) % MAX. |
Algorithm. The array is Q[MAX], with front = rear = -1 initially.
Enqueue(x)
- If
(rear + 1) % MAX == front, print "Queue overflow" and stop. - If
front == -1, setfront = rear = 0; otherwise setrear = (rear + 1) % MAX. - Set
Q[rear] = x.
Dequeue()
- If
front == -1, print "Queue underflow" and stop. - Set
x = Q[front]. - If
front == rear, setfront = rear = -1(queue becomes empty); otherwise setfront = (front + 1) % MAX. - Return
x.
void enqueue(int x) {
if ((rear + 1) % MAX == front) { printf("Overflow\n"); return; }
if (front == -1) front = rear = 0;
else rear = (rear + 1) % MAX;
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) % MAX;
return x;
}
Both operations take time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
What is B-tree? How insertions and deletions of elements can be done in a B-tree.
Answer
B-tree. A B-tree of order is a balanced multiway search tree used for disk-based storage (databases, file systems). Its properties:
- Every node has at most children and at most keys.
- Every non-root internal node has at least children; the root has at least 2 children (if not a leaf).
- Keys inside a node are sorted, and a node with keys has children, with child sub-trees holding keys in the ranges between the keys.
- All leaves are at the same level, so the tree is always height-balanced.
Search, insertion and deletion take time.
Insertion
- Search for the leaf where the key belongs.
- Insert the key into that leaf in sorted order.
- If the leaf now has more than keys (overflow), split it: the median key moves up to the parent, and the keys left and right of it form two nodes.
- If the parent overflows, repeat the split upward. If the root splits, a new root is created and the tree grows by one level.
Example (order 3, max 2 keys): insert 10, 20 gives [10, 20]. Insert 30: overflow [10, 20, 30]; median 20 moves up, giving root [20] with children [10] and [30].
Deletion
- Locate the key.
- If it is in a leaf, remove it. If it is in an internal node, replace it with its in-order predecessor or successor (from a leaf) and delete that from the leaf.
- If the node now has fewer than the minimum number of keys (underflow):
- Borrow: if an adjacent sibling has more than the minimum, rotate a key through the parent.
- Merge: otherwise merge the node with a sibling together with the separating key from the parent.
- If the merge makes the parent underflow, repeat upward. If the root becomes empty, the merged node becomes the new root and the height decreases by one.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
Explain the different ways to represent a graph. For the following graph use Prim's algorithm to find a minimum spanning tree starting from the node 'A'.
Answer
Ways to represent a graph
- Adjacency matrix. A matrix where (or the edge weight) if there is an edge from to , otherwise 0. Edge lookup is , but it needs space, so it suits dense graphs. For undirected graphs it is symmetric.
- Adjacency list. An array of lists where list holds all vertices adjacent to (with weights). It needs space and suits sparse graphs.
- Incidence matrix. A matrix where entry is 1 if edge is incident on vertex (for directed graphs +1 and -1 for tail and head).
- Edge list. A list of all edges as (u, v, w) triples.
Prim's algorithm. Start from a vertex and repeatedly add the cheapest edge that connects a tree vertex to a non-tree vertex, until all vertices are included.
The graph of the question is not reproduced, so the method is shown on this graph: A-B = 7, A-D = 5, B-C = 8, B-D = 9, B-E = 7, C-E = 5, D-E = 15, D-F = 6, E-F = 8, E-G = 9, F-G = 11. Start at A.
| Step | Candidate edges | Edge chosen | Tree vertices |
|---|---|---|---|
| 1 | A-B 7, A-D 5 | A-D (5) | A, D |
| 2 | A-B 7, D-B 9, D-E 15, D-F 6 | D-F (6) | A, D, F |
| 3 | A-B 7, D-B 9, D-E 15, F-E 8, F-G 11 | A-B (7) | A, D, F, B |
| 4 | B-C 8, B-E 7, F-E 8, F-G 11 | B-E (7) | + E |
| 5 | B-C 8, E-C 5, E-G 9, F-G 11 | E-C (5) | + C |
| 6 | E-G 9, F-G 11 | E-G (9) | + G |
Minimum spanning tree edges: A-D, D-F, A-B, B-E, E-C, E-G.
Total weight .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Explain stack as ADT. Describe push and pop operation in stack.
Answer
Stack as an ADT. A stack is an Abstract Data Type: it is defined by its data (an ordered collection of elements) and by its operations, with the LIFO rule (last in, first out), independent of implementation. The operations are:
push(x): insert x at the top.pop(): remove and return the top element.peek()/top(): read the top without removing it.isEmpty()andisFull(): check state.
It can be implemented with an array or a linked list.
Push (array of size MAX, top = -1 initially)
- If
top == MAX - 1, report "Stack overflow" and stop. - Set
top = top + 1. - Set
S[top] = x.
Pop
- If
top == -1, report "Stack underflow" and stop. - Set
x = S[top]. - Set
top = top - 1. - Return
x.
Both operations take time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Define linear and circular queue. Write are the limitation of linear queue? How circular queue can used to overcome the limitation of linear queue.
Answer
Linear queue. A linear data structure in which insertion takes place at the rear and deletion at the front (FIFO), implemented in an array with indices front and rear that only move forward.
Circular queue. A queue in which the last position of the array is joined to the first, so rear and front wrap around using modulo arithmetic: rear = (rear + 1) % MAX.
Limitation of linear queue. When items are dequeued, front moves forward and the freed slots at the beginning can never be reused. Once rear reaches MAX - 1, the queue is reported full even though empty slots exist at the front (false overflow). This wastes memory.
How the circular queue overcomes it. After rear reaches the last position, the next item is stored at index 0 if that slot is free, since (MAX - 1 + 1) % MAX = 0. Freed slots are therefore reused, and the queue is full only when (rear + 1) % MAX == front, i.e. when all slots are actually occupied.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is recursion? Write an algorithm to solve Tower of Hanoi problem.
Answer
Recursion is a technique in which a function calls itself to solve smaller instances of a problem, with a base case that ends the calls.
Tower of Hanoi algorithm. Move disks from peg A (source) to peg C (destination) using peg B (auxiliary), never putting a larger disk on a smaller one.
HANOI(n, source, destination, auxiliary)
1. If n == 1:
move disk 1 from source to destination
return
2. HANOI(n-1, source, auxiliary, destination)
3. move disk n from source to destination
4. HANOI(n-1, auxiliary, destination, source)
void hanoi(int n, char s, char d, char a) {
if (n == 1) { printf("Move disk 1 from %c to %c\n", s, d); return; }
hanoi(n - 1, s, a, d);
printf("Move disk %d from %c to %c\n", n, s, d);
hanoi(n - 1, a, d, s);
}
For : move 1 from A to B, move 2 from A to C, move 1 from B to C (3 moves). In general the number of moves is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Differentiate between internal sorting and external sorting algorithm. Explain insertion sorting algorithm with example.
Answer
Internal vs external sorting
| Internal sorting | External sorting |
|---|---|
| All data fits in main memory (RAM). | Data is too large for RAM and resides on disk/tape. |
| Fast random access to elements. | Data is processed in chunks, with heavy disk I/O. |
| Examples: bubble, insertion, quick, heap sort. | Examples: external merge sort, polyphase merge sort. |
Insertion sort. The array is divided into a sorted part (left) and an unsorted part. Each element in turn is taken and inserted into its correct position in the sorted part by shifting larger elements right.
for (i = 1; i < n; i++) {
key = a[i];
j = i - 1;
while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
a[j + 1] = key;
}
Example: 5, 2, 4, 6, 1, 3
| Pass | Key | Array |
|---|---|---|
| 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: worst and average, best case (already sorted).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
How graph can be represented using adjacency matrix? Explain Depth first traversal in a graph with suitable example.
Answer
Adjacency matrix representation. A graph with vertices is stored in an matrix , where if there is an edge between vertex and vertex , otherwise 0 (for weighted graphs, the weight is stored). The matrix of an undirected graph is symmetric.
For the graph with edges A-B, A-C, B-D, C-D, D-E:
| A | B | C | D | E | |
|---|---|---|---|---|---|
| A | 0 | 1 | 1 | 0 | 0 |
| B | 1 | 0 | 0 | 1 | 0 |
| C | 1 | 0 | 0 | 1 | 0 |
| D | 0 | 1 | 1 | 0 | 1 |
| E | 0 | 0 | 0 | 1 | 0 |
It needs space and checks whether an edge exists in .
Depth First Traversal (DFS). Start at a vertex, visit it, then move to an unvisited neighbour and continue as deep as possible; when no unvisited neighbour remains, backtrack. A stack (or recursion) is used.
- Push the start vertex and mark it visited.
- Look at the top vertex: if it has an unvisited neighbour, visit, mark and push it; otherwise pop.
- Repeat until the stack is empty.
Example (graph above, start at A, scanning the matrix row from left to right):
| Step | Visit | Stack |
|---|---|---|
| 1 | A | A |
| 2 | B | A, B |
| 3 | D | A, B, D |
| 4 | C | A, B, D, C |
| 5 | pop C (no new neighbours) | A, B, D |
| 6 | E | A, B, D, E |
| 7 | pop all | empty |
DFS order: A, B, D, C, E. With an adjacency matrix the time is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
A binary tree T has 9 nodes. The inorder and preorder traversals of T yield the following sequence of nodes:
In-order: R Z J T K H N M P
Pre-order: K Z R T J N H P M
Draw the tree T.
OR
Write short notes on:
a. Deterministic and non-deterministic algorithm
b. Divide and conquer algorithm
Answer
Constructing the tree from the traversals
Preorder gives the root first; inorder splits the nodes into left and right subtrees.
- Preorder: K Z R T J N H P M, so the root is K.
- Inorder: R Z J T K H N M P. Left of K is {R, Z, J, T} and right of K is {H, N, M, P}.
Left subtree (preorder Z R T J, inorder R Z J T): root is Z. Inorder puts R left of Z and {J, T} right of Z. For {J, T} the preorder is T J, so T is the root and J (before T in inorder) is its left child.
Right subtree (preorder N H P M, inorder H N M P): root is N. H is left of N and {M, P} is right of N. For {M, P} the preorder is P M, so P is the root and M is its left child.
The tree T
K
/ \
Z N
/ \ / \
R T H P
/ /
J M
Check: preorder (root, left, right) is K Z R T J N H P M and inorder (left, root, right) is R Z J T K H N M P. Both match the given sequences, and the tree has 9 nodes.
OR: Short notes
(a) Deterministic and non-deterministic algorithm
A deterministic algorithm produces the same output by passing through the same sequence of steps for a given input. Every step has exactly one next step. Examples are binary search, merge sort and Dijkstra's algorithm.
A non-deterministic algorithm may have several possible choices at a step. It uses a conceptual operation choice(S) that picks an element of a set , failure() to signal an unsuccessful computation and success() to signal completion. It is assumed to always make the correct choice if one exists, so it finds the answer in polynomial time on an imaginary machine. Such algorithms define the class NP, for example guessing a satisfying assignment in SAT and then verifying it. Deterministic algorithms are the ones that run on real computers.
(b) Divide and conquer algorithm
It is a design technique with three steps:
- Divide the problem into smaller sub-problems of the same type.
- Conquer by solving each sub-problem recursively (a small enough problem is solved directly).
- Combine the sub-solutions into the solution of the original problem.
Its running time is usually expressed by a recurrence such as . Examples are merge sort (), quick sort, binary search and Strassen's matrix multiplication.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
Describe types of linked list. Write an algorithm to perform following operation in circular linked list:
• Insert node at the beginning of circular linked list.
• Insert node at the end of circular linked list.
• Delete node from the beginning of circular linked list.
• Delete node from the end of circular linked list.
Answer
Types of linked list
A linked list is a linear collection of nodes where each node holds data and a pointer to another node. The main types are:
- Singly linked list: each node has data and a
nextpointer; traversal is only forward, and the last node'snextis NULL. - Doubly linked list: each node has
prev, data andnextpointers, so traversal is possible in both directions. - Circular singly linked list: the last node's
nextpoints back to the first node, so there is no NULL pointer. - Circular doubly linked list: a doubly linked list in which the last node's
nextpoints to the first and the first node'sprevpoints to the last.
Circular linked list operations
Let last be a pointer to the last node, so last->next is the first node. With this representation insertion at both ends takes time. The list is empty when last = NULL. Each node has fields info and next.
1. Insert at the beginning
InsertBegin(last, x)
1. Create node new; new->info = x
2. If last == NULL:
last = new
new->next = new
Else:
new->next = last->next
last->next = new
3. Return last
2. Insert at the end
InsertEnd(last, x)
1. Create node new; new->info = x
2. If last == NULL:
last = new
new->next = new
Else:
new->next = last->next
last->next = new
last = new
3. Return last
3. Delete from the beginning
DeleteBegin(last)
1. If last == NULL: print "Underflow"; return
2. temp = last->next
3. If temp == last: // only one node
last = NULL
Else:
last->next = temp->next
4. Free(temp)
5. Return last
4. Delete from the end
DeleteEnd(last)
1. If last == NULL: print "Underflow"; return
2. If last->next == last: // only one node
Free(last); last = NULL; return
3. p = last->next
4. While p->next != last:
p = p->next
5. p->next = last->next // p becomes the new last node
6. Free(last)
7. last = p
8. Return last
Deletion at the end needs a traversal, so it takes time; the other three operations take .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
Differentiate between strict binary tree and skewed tree. Explain binary search tree and insertion and deletion operation in BST in detail. Consider following data and construct BST: 14, 11, 12, 19, 15, 22, 13, 8, 33, 7, 9, 20.
Answer
Strict binary tree vs skewed tree
| Strict (full) binary tree | Skewed tree |
|---|---|
| Every node has either 0 or 2 children. | Every node has only one child, so the tree is a chain. |
| A tree with leaves has nodes. | A tree with nodes has height . |
| Height is small (about if it is also complete). | Height is the maximum possible. |
| Searching and traversal are efficient. | Behaves like a linked list; search is . |
| Example: root with two children, each of which has two children or none. | Left skewed: every node has only a left child. Right skewed: every node has only a right child. |
Binary search tree (BST)
A BST is a binary tree in which, for every node, all keys in its left subtree are smaller than the node's key and all keys in its right subtree are larger (duplicates are normally not allowed). Its inorder traversal gives the keys in sorted order. Search, insertion and deletion take time, where is the height: for a balanced tree and for a skewed one.
Insertion
- If the tree is empty, the new node becomes the root.
- Otherwise compare the key with the current node: go left if it is smaller, right if it is larger.
- Repeat until a NULL link is reached and attach the new node there.
Insert(root, key)
if root == NULL: return newNode(key)
if key < root->info: root->left = Insert(root->left, key)
else if key > root->info: root->right = Insert(root->right, key)
return root
Deletion
First find the node, then there are three cases:
- Leaf node: remove it and set the parent's link to NULL.
- One child: replace the node by its child (the parent now points to that child).
- Two children: replace the node's key with its inorder successor (the smallest key in the right subtree) or inorder predecessor (the largest key in the left subtree), then delete that successor/predecessor node, which has at most one child.
Constructing the BST for 14, 11, 12, 19, 15, 22, 13, 8, 33, 7, 9, 20
- 14 is the root.
- 11 < 14: left of 14.
- 12 < 14, > 11: right of 11.
- 19 > 14: right of 14.
- 15 > 14, < 19: left of 19.
- 22 > 19: right of 19.
- 13 < 14, > 11, > 12: right of 12.
- 8 < 11: left of 11.
- 33 > 19, > 22: right of 22.
- 7 < 11, < 8: left of 8.
- 9 < 11, > 8: right of 8.
- 20 > 19, < 22: left of 22.
14
/ \
11 19
/ \ / \
8 12 15 22
/ \ \ / \
7 9 13 20 33
Inorder check: 7, 8, 9, 11, 12, 13, 14, 15, 19, 20, 22, 33, which is sorted.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
What is priority queue? Explain sequential searching algorithm and binary searching algorithm with suitable illustration.
Answer
Priority queue
A priority queue is an abstract data type in which every element has a priority and elements are removed in order of priority rather than order of arrival. In a max priority queue the element with the highest priority is removed first; in a min priority queue the lowest value comes first. If two elements have equal priority they are served in FIFO order. Operations are insert(x, p), delete (remove the highest-priority element) and peek. It can be implemented with an ordered array or list, an unordered list, or most efficiently with a heap, where insertion and deletion take . Uses include CPU scheduling, Dijkstra's shortest path and Huffman coding.
Sequential (linear) search
The key is compared with each element of the list from the first to the last until it is found or the list ends. The list need not be sorted.
LinearSearch(A, n, key)
for i = 0 to n-1
if A[i] == key: return i
return -1
Illustration: A = {8, 3, 7, 5, 9}, key = 5. Compare with 8 (no), 3 (no), 7 (no), 5 (yes), so it is found at index 3 after 4 comparisons.
Complexity: best case , worst and average case .
Binary search
It works only on a sorted array. The key is compared with the middle element; if equal, the search ends, if smaller the search continues in the left half, otherwise in the right half.
BinarySearch(A, low, high, key)
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
Illustration: A = {5, 12, 18, 23, 31, 40, 57}, indices 0 to 6, key = 40.
- low = 0, high = 6, mid = 3, A[3] = 23 < 40, so low = 4.
- low = 4, high = 6, mid = 5, A[5] = 40, found at index 5.
Each step halves the search range, so the worst-case time is and the best case is . Binary search is much faster than linear search for large sorted data, but needs sorted data and random access.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BCA 2019 Third Semester Data Structures and Algorithms (TU board exam, 2019), TU BCA 2019 Third Semester Data Structures and Algorithms (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester Data Structures and Algorithms (TU board exam, 2020), TU BCA 2021 Third Semester Data Structures and Algorithms (TU board exam, 2021), TU BCA 2022 Third Semester Data Structures and Algorithms (TU board exam, 2022), TU BCA 2023 Third Semester Data Structures and Algorithms (TU board exam, 2023), TU BCA 2024 Third Semester Data Structures and Algorithms (TU board exam, 2024), TU BCA 2025 Third Semester Data Structures and Algorithms (TU board exam, 2025), TU BCA 2019 Third Semester OOP in Java (TU board exam, 2019), TU BCA 2019 Third Semester OOP in Java (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester OOP in Java (TU board exam, 2020), TU BCA 2021 Third Semester OOP in Java (TU board exam, 2021), TU BCA 2022 Third Semester OOP in Java (TU board exam, 2022), TU BCA 2023 Third Semester OOP in Java (TU board exam, 2023), TU BCA 2024 Third Semester OOP in Java (TU board exam, 2024), TU BCA 2025 Third Semester OOP in Java (TU board exam, 2025), TU BCA 2019 Third Semester Probability and Statistics (TU board exam, 2019), TU BCA 2019 Third Semester Probability and Statistics (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester Probability and Statistics (TU board exam, 2020), TU BCA 2021 Third Semester Probability and Statistics (TU board exam, 2021), TU BCA 2022 Third Semester Probability and Statistics (TU board exam, 2022), TU BCA 2023 Third Semester Probability and Statistics (TU board exam, 2023), TU BCA 2024 Third Semester Probability and Statistics (TU board exam, 2024), TU BCA 2025 Third Semester Probability and Statistics (TU board exam, 2025), TU BCA 2019 Third Semester System Analysis and Design (TU board exam, 2019), TU BCA 2019 Third Semester System Analysis and Design (TU board exam, listed as 2019 (a second 2019 set in the compilation)), TU BCA 2019 Third Semester System Analysis and Design (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester System Analysis and Design (TU board exam, 2020), TU BCA 2021 Third Semester System Analysis and Design (TU board exam, 2021), TU BCA 2022 Third Semester System Analysis and Design (TU board exam, 2022), TU BCA 2023 Third Semester System Analysis and Design (TU board exam, 2023), TU BCA 2024 Third Semester System Analysis and Design (TU board exam, 2024), TU BCA 2025 Third Semester System Analysis and Design (TU board exam, 2025), TU BCA 2019 Third Semester Web Technology (TU board exam, 2019), TU BCA 2019 Third Semester Web Technology (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester Web Technology (TU board exam, 2020), TU BCA 2021 Third Semester Web Technology (TU board exam, 2021), TU BCA 2022 Third Semester Web Technology (TU board exam, 2022), TU BCA 2023 Third Semester Web Technology (TU board exam, 2023), TU BCA 2024 Third Semester Web Technology (TU board exam, 2024) and TU BCA 2025 Third Semester Web Technology (TU board exam, 2025). Answers are written for this site; check them against your class notes.