Chapter 1
Data Structures and Algorithms
TU BIT past exam questions
Past questions and answers
60 questions set from this chapter. Most repeated first.
- 2078 · 10 marks
Explain algorithm to convert an infix expression to postfix using stack? Use this algorithm to convert (A+B)*C-D to postfix.
Similar questions: Convert the infix expression 7 * (2082)
Answer
Infix to postfix using a stack
Operands stay in the order they appear; operators are held on a stack until operators of higher or equal precedence above them are popped. Precedence: ^ highest, then * /, then + -; ( has the lowest precedence while on the stack.
Algorithm
- Create an empty stack and an empty output string.
- Scan the infix expression from left to right.
- If the symbol is an operand, append it to the output.
- If the symbol is
(, push it. - If the symbol is
), pop operators to the output until(is found; discard both parentheses. - If the symbol is an operator, while the stack is not empty and the top is an operator of precedence greater than or equal to the current one (left associative), pop it to the output; then push the current operator.
- After the scan, pop all remaining operators to the output.
Conversion of
| Symbol | Stack (bottom to top) | Output |
|---|---|---|
| ( | ( | |
| A | ( | A |
| + | ( + | A |
| B | ( + | A B |
| ) | A B + | |
| * | * | A B + |
| C | * | A B + C |
| - | - (the * is popped first, since it has higher precedence) | A B + C * |
| D | - | A B + C * D |
| end | A B + C * D - |
Postfix expression:
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
How can you implement queue using linked list? Explain.
Similar questions: How can we use linked list (2080)
Answer
Queue using a linked list
A queue follows FIFO order. With a singly linked list, keep two pointers: front (the first node, where deletion occurs) and rear (the last node, where insertion occurs). The queue can grow dynamically, so there is no overflow except when memory is exhausted.
struct node { int data; struct node *next; };
struct node *front = NULL, *rear = NULL;
Enqueue (insert at rear):
- Create a new node, set its data and
next = NULL. - If the queue is empty, set
front = rear = new. - Otherwise set
rear->next = newandrear = new.
Dequeue (delete from front):
- If
front == NULL, report underflow. - Otherwise save
temp = front, setfront = front->next. - If
frontbecomes NULL, setrear = NULL. - Free
tempand return its data.
Both operations take time. Memory is allocated only as needed, at the cost of one extra pointer per element.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Explain different applications of binary tree.
Similar questions: What are different applications of binary (2080)
Answer
Applications of binary tree
A binary tree is a tree in which each node has at most two children (left and right).
Applications
- Binary search tree (BST): searching, insertion and deletion in on average.
- Expression trees: evaluating and converting arithmetic expressions; traversals give prefix, infix and postfix forms.
- Heap and priority queue: a complete binary tree used for heap sort and priority queues.
- Huffman coding: a binary tree of character frequencies gives prefix codes for data compression.
- Decision trees and game trees: each node represents a decision or a game state with two outcomes.
- Routing and symbol tables: binary tries in routers, balanced trees (AVL, red-black) in compilers and databases.
- Sorting: tree sort by inorder traversal of a BST.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
How can we use linked list to implement queue? Explain.
Similar questions: How can you implement queue using (2078)
Answer
Queue using a linked list
A queue (FIFO) can be built from a singly linked list with two pointers: front at the first node (deletion) and rear at the last node (insertion). It grows and shrinks dynamically with no fixed size.
struct node { int data; struct node *next; };
struct node *front = NULL, *rear = NULL;
Enqueue(x): allocate a node with data = x, next = NULL. If rear == NULL, set front = rear = node; else rear->next = node; rear = node.
Dequeue(): if front == NULL, underflow. Otherwise temp = front; front = front->next; if front == NULL set rear = NULL; free temp.
Both operations are . Unlike an array queue, no space is wasted and overflow occurs only when memory runs out; each node needs an extra pointer.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What are different applications of binary tree? Explain.
Similar questions: Explain different applications of binary tree. (2079)
Answer
Applications of binary tree
A binary tree is a tree in which each node has at most two children (left and right).
Applications
- Binary search tree (BST): searching, insertion and deletion in on average.
- Expression trees: evaluating and converting arithmetic expressions; traversals give prefix, infix and postfix forms.
- Heap and priority queue: a complete binary tree used for heap sort and priority queues.
- Huffman coding: a binary tree of character frequencies gives prefix codes for data compression.
- Decision trees and game trees: each node represents a decision or a game state with two outcomes.
- Routing and symbol tables: binary tries in routers, balanced trees (AVL, red-black) in compilers and databases.
- Sorting: tree sort by inorder traversal of a BST.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Convert the infix expression 7 * 8 + 10 - 2 to postfix using stack.
Similar questions: Explain algorithm to convert an infix (2078)
Answer
Infix:
Precedence: * is higher than + and -. + and - have equal precedence and are left associative.
Scan left to right. Operands go straight to the output. An operator pops from the stack every operator of greater or equal precedence, and is then pushed.
| Symbol | Stack | Postfix output |
|---|---|---|
| 7 | 7 | |
| * | * | 7 |
| 8 | * | 7 8 |
| + | + (pop *) | 7 8 * |
| 10 | + | 7 8 * 10 |
| - | - (pop +) | 7 8 * 10 + |
| 2 | - | 7 8 * 10 + 2 |
| end | (pop -) | 7 8 * 10 + 2 - |
Postfix: 7 8 * 10 + 2 -
Check: , , . This equals the value of the infix expression.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
What is shortest path algorithm? Use Dijkstra's algorithm to find shortest path between the vertices of a and z in the graph given below.
Answer
Shortest path algorithm
A shortest path algorithm finds a path between two vertices of a weighted graph such that the sum of the edge weights along the path is minimum. Dijkstra's algorithm solves the single-source shortest path problem for graphs with non-negative edge weights, in with an array or with a priority queue.
Dijkstra's algorithm
- Set and for all other vertices; mark all vertices unvisited.
- Pick the unvisited vertex with the smallest and mark it visited (permanent).
- For every unvisited neighbour of : if , set and .
- Repeat steps 2-3 until is visited (or all vertices are visited).
- Trace the path back from using .
Worked example (graph with edges a-b 4, a-c 2, b-c 1, b-d 5, c-d 8, c-e 10, d-e 2, d-z 6, e-z 3)
| Step | Vertex fixed | a | b | c | d | e | z |
|---|---|---|---|---|---|---|---|
| 0 | a (0) | 0 | 4 | 2 | |||
| 1 | c (2) | 0 | 3 | 2 | 10 | 12 | |
| 2 | b (3) | 0 | 3 | 2 | 8 | 12 | |
| 3 | d (8) | 0 | 3 | 2 | 8 | 10 | 14 |
| 4 | e (10) | 0 | 3 | 2 | 8 | 10 | 13 |
| 5 | z (13) | 0 | 3 | 2 | 8 | 10 | 13 |
Tracing predecessors: .
Shortest path: with total length .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
Explain merge sort along with its time complexity. Use this algorithm to sort array of numbers given below: 25, 37, 48, 25, 23, 17, 31, 45, 7, 21, 15, 8, 11
Answer
Merge sort
Merge sort is a divide-and-conquer sorting algorithm.
- Divide: split the array into two halves.
- Conquer: recursively sort each half (an array of one element is already sorted).
- Combine: merge the two sorted halves into one sorted array by repeatedly taking the smaller of the front elements of the two halves.
MergeSort(A, low, high)
if low < high
mid = (low + high) / 2
MergeSort(A, low, mid)
MergeSort(A, mid+1, high)
Merge(A, low, mid, high)
Time complexity: the array is halved times and each level needs work to merge, so
This holds for the best, average and worst cases. It needs extra space and is stable.
Sorting 25, 37, 48, 25, 23, 17, 31, 45, 7, 21, 15, 8, 11
Divide:
- [25 37 48 25 23 17 31] and [45 7 21 15 8 11]
- [25 37 48 25] [23 17 31] and [45 7 21] [15 8 11]
- [25 37] [48 25] [23 17] [31] and [45 7] [21] [15 8] [11]
Merge:
- [25 37], [25 48], [17 23], [31], [7 45], [21], [8 15], [11]
- [25 25 37 48], [17 23 31], [7 21 45], [8 11 15]
- [17 23 25 25 31 37 48], [7 8 11 15 21 45]
- Final merge: 7, 8, 11, 15, 17, 21, 23, 25, 25, 31, 37, 45, 48
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is data Structure? Explain an array as an abstract data type.
Answer
Data structure
A data structure is a way of organising, storing and managing data in a computer so that it can be accessed and modified efficiently. Examples: array, stack, queue, linked list, tree, graph. They are classified as primitive (int, char, float) and non-primitive (linear: array, list, stack, queue; non-linear: tree, graph).
Array as an abstract data type
An abstract data type (ADT) specifies a set of data and the operations on it, without saying how they are implemented. The array ADT is a fixed-size collection of elements of the same type, each identified by an index.
- Data: a sequence of elements of one type, stored in contiguous memory, with indices .
- Operations:
create(n): make an array of sizeget(i): return the element at indexset(i, x): store at indexinsert(i, x),delete(i): add or remove an element, shifting otherstraverse(),search(x),length()
Address of element is , so access is ; insertion and deletion are because of shifting. The user only uses the operations and need not know how the array is stored, which is what makes it an ADT.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Explain big oh(O) notation with suitable example.
Answer
Big O notation
Big O gives an asymptotic upper bound on the growth of a function, used for the worst-case running time of an algorithm.
if there exist positive constants and such that
Example: . For , , so with and we get .
Similarly , since for .
Common orders: . For example linear search is and binary search is . Constants and lower-order terms are ignored.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Define priority queue. How do you implement priority queue? Explain.
Answer
Priority queue
A priority queue is a queue in which each element has a priority, and the element with the highest priority (or lowest, in a min-priority queue) is removed first, regardless of its arrival order. Elements of equal priority are served in FIFO order.
Implementation
- Unsorted array or list: insert at the end in ; deletion searches for the highest-priority element in .
- Sorted array or list: insert at the correct position in ; deletion removes the front element in .
- Multiple queues: one ordinary queue per priority level; always dequeue from the non-empty queue with the highest priority.
- Heap: a binary heap gives insertion and deletion both in . This is the most efficient implementation.
Basic operations: insert(item, priority), deleteHighest(), peek(), isEmpty().
Applications: CPU scheduling, Dijkstra's algorithm, Huffman coding, event simulation.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Define recursion. Explain Tower of Hanoi algorithm in detail.
Answer
Recursion
Recursion is a technique in which a function calls itself, directly or indirectly, to solve a smaller instance of the same problem. A recursive function must have a base case (which stops the recursion) and a recursive case that moves towards the base case. Each call is kept on the call stack.
Tower of Hanoi
There are three pegs (source A, auxiliary B, destination C) and disks of different sizes stacked on A with the smallest on top. Move all the disks to C so that:
- only one disk is moved at a time,
- only the top disk of a peg can be moved,
- a larger disk is never placed on a smaller one.
Recursive solution:
- Move the top disks from A to B using C.
- Move the largest disk from A to C.
- Move the disks from B to C using A.
TOH(n, A, B, C)
if n == 1
print "Move disk 1 from A to C"; return
TOH(n-1, A, C, B)
print "Move disk n from A to C"
TOH(n-1, B, A, C)
Number of moves: , , giving
For the 7 moves are: A→C, A→B, C→B, A→C, B→A, B→C, A→C. The time complexity is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is binary tree? Explain different application of binary tree.
Answer
Binary tree
A binary tree is a tree in which every node has at most two children, called the left child and the right child. It is either empty or consists of a root and a left and right subtree, each itself a binary tree. Types include full, complete, almost complete and binary search trees.
Applications
- Binary search tree (BST): searching, insertion and deletion in on average.
- Expression trees: evaluating and converting arithmetic expressions; traversals give prefix, infix and postfix forms.
- Heap and priority queue: a complete binary tree used for heap sort and priority queues.
- Huffman coding: a binary tree of character frequencies gives prefix codes for data compression.
- Decision trees and game trees: each node represents a decision or a game state with two outcomes.
- Routing and symbol tables: binary tries in routers, balanced trees (AVL, red-black) in compilers and databases.
- Sorting: tree sort by inorder traversal of a BST.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Explain sequential search. How is it different from binary search?
Answer
Sequential (linear) search
Sequential search examines the elements of a list one by one from the beginning, comparing each with the key, until a match is found or the list ends.
LinearSearch(A, n, key)
for i = 0 to n-1
if A[i] == key return i
return -1
Time: best case , average and worst . It works on unsorted data and on linked lists.
Difference from binary search
| Basis | Sequential search | Binary search |
|---|---|---|
| Data order | Not required to be sorted | Must be sorted |
| Method | Checks every element in turn | Compares with the middle and discards half |
| Worst-case time | ||
| Structure | Array or linked list | Needs random access (array) |
| Implementation | Simple | More complex |
| Suitable for | Small or unsorted lists | Large sorted lists |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Define hashing. Explain quadratic probing with example.
Answer
Hashing
Hashing is a technique that maps a key to an index in a table using a hash function, , so that records can be stored and retrieved in average time. For example for table size .
Collision and quadratic probing
A collision occurs when two keys map to the same index. Quadratic probing is an open addressing method: if slot is occupied, probe
This reduces the primary clustering of linear probing.
Example: table size , insert 23, 43, 13, 33 with .
- 23 goes to index 3.
- 43: index 3 is full; : , so it goes to index 4.
- 13: index 3 full; index 4 full; : , so it goes to index 7.
- 33: index 3 full; 4 full; 7 full; : , so it goes to index 2.
Final table: index 2 = 33, 3 = 23, 4 = 43, 7 = 13.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is graph traversal? Explain breadth first search.
Answer
Graph traversal
Graph traversal is visiting every vertex of a graph exactly once in a systematic way, starting from a given vertex. The two standard methods are breadth first search (BFS) and depth first search (DFS).
Breadth first search (BFS)
BFS visits the start vertex, then all its neighbours, then all their unvisited neighbours, and so on, level by level. It uses a queue and a visited array.
- Mark the start vertex visited and enqueue it.
- While the queue is not empty: dequeue a vertex and process it; for each unvisited neighbour of , mark it visited and enqueue it.
Example: edges A-B, A-C, B-D, C-D, C-E, starting at A.
- Queue: A. Visit A; enqueue B, C.
- Visit B; enqueue D. Visit C; enqueue E.
- Visit D, then E.
BFS order: A, B, C, D, E.
Time complexity is with an adjacency list. BFS finds the shortest path (fewest edges) in an unweighted graph.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
How stack is used in recursion? Explain different stack operations. Explain algorithm to convert an infix expression to postfix using stack.
Answer
Stack in recursion
Each recursive call creates an activation record (parameters, local variables and return address) that is pushed on the system stack. When a call finishes, its record is popped and control returns to the caller. This LIFO behaviour is what allows nested calls to return correctly. For example, fact(3) pushes fact(3), fact(2), fact(1), fact(0) and then pops them in reverse while multiplying.
Stack and its operations
A stack is a linear data structure in which insertion and deletion take place only at one end, the top (LIFO).
push(x): add at the top (overflow if full).pop(): remove and return the top element (underflow if empty).peek()/top(): return the top element without removing it.isEmpty(),isFull().
All operations take time.
Infix to postfix algorithm
- Scan the infix expression left to right with an empty operator stack.
- Operand: append to output.
(: push.): pop to output until(; discard the parentheses.- Operator: while the top of the stack is an operator with precedence greater than or equal to the current one, pop it to output; then push the current operator.
- At the end, pop all remaining operators to output.
Example: becomes , because * has higher precedence than + and stays above it on the stack.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Explain complete binary tree with example. Starting with an empty binary search tree, show the effect of successively adding the following elements: 47, 50, 25, 27, 17, 61, 5, and 26. Also, traverse the resulting tree in pre-order, in-order, and post-order.
Answer
Complete binary tree
A complete binary tree of height is a binary tree in which every level is completely filled, and every internal node has exactly two children. It has nodes (and leaves). A tree with all levels full is also called perfect.
Example, height 2:
A
/ \
B C
/ \ / \
D E F G
Building the BST: 47, 50, 25, 27, 17, 61, 5, 26
- 47 is the root.
- 50 > 47: right of 47.
- 25 < 47: left of 47.
- 27 < 47, > 25: right of 25.
- 17 < 47, < 25: left of 25.
- 61 > 47, > 50: right of 50.
- 5 < 47, < 25, < 17: left of 17.
- 26 < 47, > 25, < 27: left of 27.
47
/ \
25 50
/ \ \
17 27 61
/ /
5 26
Traversals
- Pre-order (root, left, right): 47, 25, 17, 5, 27, 26, 50, 61
- In-order (left, root, right): 5, 17, 25, 26, 27, 47, 50, 61
- Post-order (left, right, root): 5, 17, 26, 27, 25, 61, 50, 47
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Explain quick sort algorithm. Use this algorithm to sort the numbers 35, 82, 18, 54, 13, 31, 20, 69, and 19.
Answer
Quick sort
Quick sort is a divide-and-conquer algorithm.
- Choose a pivot element (here, the first element).
- Partition: rearrange so that all elements smaller than the pivot are before it and all larger ones after it; the pivot is now in its final place.
- Recursively sort the left and right parts.
QuickSort(A, low, high)
if low < high
p = Partition(A, low, high)
QuickSort(A, low, p-1)
QuickSort(A, p+1, high)
Time: average and best , worst (already sorted input with first-element pivot). It sorts in place.
Sorting 35, 82, 18, 54, 13, 31, 20, 69, 19
- Pivot 35: smaller [18, 13, 31, 20, 19], larger [82, 54, 69] gives [18, 13, 31, 20, 19] 35 [82, 54, 69]
- Left part, pivot 18: [13] 18 [31, 20, 19]
- [31, 20, 19], pivot 31: [20, 19] 31
- [20, 19], pivot 20: [19] 20
- Right part [82, 54, 69], pivot 82: [54, 69] 82
- [54, 69], pivot 54: 54 [69]
Joining the pieces gives the sorted list:
13, 18, 19, 20, 31, 35, 54, 69, 82
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Define ADT. Explain array as an ADT.
Answer
Abstract data type (ADT)
An ADT is a mathematical model of a data structure defined by its data and the operations on it, with the implementation hidden from the user. Only what is done is specified, not how. Examples: stack, queue, list.
Array as an ADT
- Data: a fixed-size, ordered collection of elements of the same type, accessed by index and stored in contiguous memory.
- Operations:
create(n): create an array of sizeget(i)/set(i, x): read or write the element at indexinsert(i, x)anddelete(i): add or remove with shiftingsearch(x),traverse(),size()
Element address , giving access; insertion and deletion are . Users work only through these operations, so the array's internal layout can change without affecting programs.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What is time complexity? Explain big oh notation with example.
Answer
Time complexity
Time complexity of an algorithm is the amount of time it needs to run as a function of the input size , measured by counting basic operations rather than seconds. It is expressed asymptotically as best, average and worst case.
Big O notation
if there are constants and such that
It gives an upper bound (worst case).
Example: . For , , so , and .
A loop running times has ; a nested double loop has ; binary search has .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Explain priority queue with example. What is circular queue?
Answer
Priority queue
A priority queue is a queue in which every element has a priority and the element with the highest priority is removed first; equal priorities follow FIFO. It can be implemented using a sorted list, an unsorted list or (best) a heap.
Example: insert (task, priority): (A, 2), (B, 5), (C, 1). With larger number meaning higher priority, deletion returns B, then A, then C, although A arrived first. In an operating system, an interrupt handler gets served before a normal process.
Circular queue
A circular queue is a linear queue in which the last position is connected back to the first, forming a circle. Insertion is done at rear = (rear + 1) % n and deletion at front = (front + 1) % n. The queue is full when (rear + 1) % n == front. It reuses the space freed by deletions, which a simple linear array queue wastes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What are the benefits of using recursion? Write a recursive function to find nth Fibonacci number.
Answer
Benefits of recursion
- Code is short, clear and closely mirrors the mathematical definition.
- Natural for problems with recursive structure: trees, graphs, divide-and-conquer (merge sort, quick sort), Tower of Hanoi, backtracking.
- Complex problems break into smaller identical subproblems, which makes them easier to design and prove correct.
- Reduces the need for explicit loops and extra variables.
(Drawbacks: stack overhead and possible stack overflow.)
Recursive function for the nth Fibonacci number
The sequence is , , .
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);
}
Example: fib(5) = 5 (sequence 0, 1, 1, 2, 3, 5). This version takes time because subproblems are recomputed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Explain singly linked list with example. Compare singly linked list with doubly linked list.
Answer
Singly linked list
A singly linked list is a dynamic linear collection of nodes; each node contains data and a pointer to the next node. A head pointer 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; };
Example: head → [10|•] → [20|•] → [30|NULL]. Inserting 15 after 10 only changes two pointers: new->next = 10's next, then 10->next = new.
Singly vs doubly linked list
| Basis | Singly linked list | Doubly linked list |
|---|---|---|
| Pointers per node | One (next) | Two (prev and next) |
| Traversal | Forward only | Forward and backward |
| Memory | Less | More |
| Deletion of a given node | Needs the previous node, | using prev |
| Implementation | Simpler | More complex |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Explain collision and collision resolution in hashing. What is double hashing?
Answer
Collision
In hashing, a collision occurs when two different keys give the same hash value, , so they compete for the same table slot.
Collision resolution
- Separate chaining (open hashing): each slot holds a linked list of all keys that hash to it.
- Open addressing (closed hashing): the key is placed in another empty slot of the table found by probing:
- linear probing:
- quadratic probing:
- double hashing
Double hashing
Double hashing uses a second hash function to decide the step size of the probe sequence:
where , for example . Different keys get different step sizes, which removes both primary and secondary clustering.
Example: , , . Insert 23 at index 3. Insert 43: index 3 is full; , so try , which is free.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Explain adjacency matrix representation of graphs with example.
Answer
Adjacency matrix representation
For a graph with vertices, the adjacency matrix is an matrix where if there is an edge from vertex to vertex , and otherwise. For a weighted graph, stores the weight of the edge (with or 0 for no edge). The matrix of an undirected graph is symmetric.
Example: vertices 1, 2, 3, 4 with edges 1-2, 1-3, 2-4, 3-4.
For a directed graph with edges 1→2, 2→3, 3→1 the matrix has 1 only at positions (1,2), (2,3), (3,1).
- Checking whether an edge exists takes .
- Space is regardless of the number of edges, so it suits dense graphs.
- The degree of a vertex is the sum of its row (undirected).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 2.5+2.5 marks
Write short notes on: (a) Linear Search (b) Minimum Spanning Tree
Answer
(a) Linear search
Linear search checks the elements of a list one after another from the first until the key is found or the list ends. It needs no sorted data.
for i = 0 to n-1
if A[i] == key return i
return -1
Best case , average and worst case .
(b) Minimum spanning tree
A spanning tree of a connected weighted graph with vertices is a subgraph that is a tree containing all vertices, with edges. The minimum spanning tree (MST) is the spanning tree with the smallest total edge weight. It is found by Kruskal's algorithm (add the lightest edges that do not form a cycle) or Prim's algorithm (grow the tree from a vertex by the cheapest edge). Applications: laying cable, road and pipeline networks, network design.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
What is stack? Explain different stack operations. Explain algorithm to evaluate postfix expression.
Answer
Stack
A stack is a linear data structure in which insertion and deletion take place only at one end, called the top. It follows LIFO (last in, first out). It can be implemented with an array or a linked list.
Operations
push(x): insert at the top; if the stack is full, report overflow.pop(): remove and return the top element; if empty, report underflow.peek(): return the top element without removing it.isEmpty()andisFull().
Each operation takes time.
Algorithm to evaluate a postfix expression
- Create an empty operand stack.
- Scan the postfix expression left to right.
- If the symbol is an operand, push it.
- If it is an operator, pop two operands: first
b(top) thena; computea op b; push the result. - At the end, the single value on the stack is the result.
Example:
- Push 5, 3, 2.
*: pop 2 and 3, push . Stack: 5, 6.+: pop 6 and 5, push 11.- Push 4.
-: pop 4 and 11, push .
Result: 7.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
Explain almost complete binary tree with example. How do you insert, search, and delete nodes in a binary search tree? Explain with suitable example?
Answer
Almost complete binary tree
An almost complete binary tree is a binary tree in which every level except possibly the last is completely filled, and the nodes of the last level are as far left as possible. A binary heap is such a tree, and it can be stored in an array (children of node at and ).
10
/ \
20 30
/ \ /
40 50 60
Binary search tree (BST) operations
In a BST, for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger.
Search(key): start at the root; if equal, found; if smaller go left, else go right; if NULL is reached, not found. Time .
Insert(key): search for the key; the NULL position where the search ends is where the new node is attached. Example: inserting 50, 30, 70, 20, 40 gives root 50, left 30 (children 20, 40), right 70. Inserting 35 goes 50 → left to 30 → right to 40 → left of 40.
Delete(key): three cases.
- Leaf node: remove it.
- One child: replace the node by its child.
- Two children: replace the node's key by its inorder successor (smallest in the right subtree) or predecessor, then delete that node.
Example: deleting 30 (children 20 and 40) in the tree above replaces it by its successor 35 (or 40), then removes the successor node.
All three operations take : for a balanced tree and in the worst (skewed) case.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
Discuss the limitation of choosing first element as pivot in quick sort. Using merge sort algorithm, sort the numbers 40, 6, 5, 21, 3, 100, 90, 7, 8, 12, 30.
Answer
Limitation of choosing the first element as pivot
If the array is already sorted (ascending or descending), or nearly so, the first element is the smallest or largest, so each partition splits the array into parts of sizes and . The recursion depth becomes and the running time degrades to
instead of . It also causes deep recursion (stack overflow risk). Remedies: choose a random pivot, the median of three, or the middle element.
Merge sort of 40, 6, 5, 21, 3, 100, 90, 7, 8, 12, 30
Divide:
- [40 6 5 21 3 100] and [90 7 8 12 30]
- [40 6 5] [21 3 100] and [90 7 8] [12 30]
- [40 6] [5] [21 3] [100] and [90 7] [8] [12] [30]
Merge:
- [6 40], [5] gives [5 6 40]; [3 21], [100] gives [3 21 100]
- [5 6 40] and [3 21 100] give [3 5 6 21 40 100]
- [7 90], [8] gives [7 8 90]; [12 30]
- [7 8 90] and [12 30] give [7 8 12 30 90]
- Final merge: 3, 5, 6, 7, 8, 12, 21, 30, 40, 90, 100
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Define data type and ADT. What are the benefits of using ADT? Explain
Answer
Data type
A data type defines a set of values and the operations allowed on them, for example int, float, char. It also fixes the memory size and representation.
Abstract data type (ADT)
An ADT is a logical description of data and the operations on it, independent of any implementation. The user knows what operations exist and what they do, not how they are coded. Examples: stack (push, pop), queue (enqueue, dequeue), list.
Benefits of using ADT
- Abstraction and information hiding: implementation details are hidden.
- Modularity: the implementation can be changed (array to linked list) without changing the code that uses it.
- Reusability: one ADT can be used in many programs.
- Easier maintenance and debugging: errors are localised.
- Clear specification that helps teamwork and correctness.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is space complexity? Explain omega notation with example.
Answer
Space complexity
Space complexity is the amount of memory an algorithm needs as a function of input size . It includes the fixed part (code, constants, simple variables) and the variable part (input data, recursion stack, dynamic memory): . For example an iterative sum of an array needs extra space; merge sort needs ; a recursive factorial uses stack space.
Omega () notation
Omega gives an asymptotic lower bound. if there are constants and such that
Example: . Since for all , with and we get . It is used for best-case running time, for example linear search is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is circular queue? How can you implement circular queue?
Answer
Circular queue
A circular queue is a queue in which the last position of the array is connected to the first, so the array is treated as a circle. It overcomes the wasted space of a linear array queue, where freed slots at the front cannot be reused after rear reaches the end.
Implementation using an array of size N
Initially front = rear = -1.
Enqueue(x):
- If
(rear + 1) % N == front, the queue is full: overflow. - If the queue is empty (
front == -1), setfront = 0. rear = (rear + 1) % N; Q[rear] = x.
Dequeue():
- If
front == -1, the queue is empty: underflow. x = Q[front].- If
front == rear, the queue becomes empty: setfront = rear = -1; otherwisefront = (front + 1) % N. - Return
x.
Both operations take time. The modulus makes the indices wrap around to 0 after .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Define recursion. Explain Tower of Hanoi (TOH) with example.
Answer
Recursion
Recursion is a technique in which a function calls itself to solve smaller instances of the same problem. It needs a base case to stop and a recursive case that moves towards it. Example: with .
Tower of Hanoi (TOH)
Given three pegs A (source), B (auxiliary), C (destination) and disks of decreasing size on A, move all disks to C, moving one disk at a time, taking only the top disk, and never placing a larger disk on a smaller one.
Recursive idea: move disks A→B, move the largest disk A→C, move disks B→C.
TOH(n, A, B, C)
if n == 0 return
TOH(n-1, A, C, B)
print "Move disk n from A to C"
TOH(n-1, B, A, C)
Example, (7 moves): disk 1 A→C, disk 2 A→B, disk 1 C→B, disk 3 A→C, disk 1 B→A, disk 2 B→C, disk 1 A→C.
Number of moves , so the time complexity is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Why do we need hashing? Explain quadratic probing.
Answer
Need for hashing
Searching in an array or list takes and in a balanced tree or sorted array . Hashing uses a hash function to compute the table index of a key directly, giving average time for insertion, search and deletion. It is used in symbol tables, databases, caches, password storage and dictionaries, especially for large data.
Quadratic probing
A collision happens when two keys hash to the same slot. Quadratic probing resolves it in an open addressing table of size by trying the slots
until an empty slot is found. It avoids the primary clustering of linear probing, but keys with the same initial hash follow the same probe sequence (secondary clustering).
Example: , ; insert 22, 33, 44.
- 22 goes to index 0.
- 33: index 0 is full; : index 1 is free, so 33 goes to index 1.
- 44: index 0 full; index 1 full; : , so 44 goes to index 4.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Define spanning tree. Explain minimum spanning tree with example.
Answer
Spanning tree
A spanning tree of a connected undirected graph with vertices is a subgraph that includes all vertices, is connected and has no cycles; it therefore has exactly edges.
Minimum spanning tree (MST)
In a weighted graph, the MST is the spanning tree whose total edge weight is the smallest. Algorithms:
- Kruskal's: sort edges by weight and add each edge if it does not form a cycle.
- Prim's: start from any vertex and repeatedly add the cheapest edge connecting the tree to a new vertex.
Example: vertices A, B, C, D; edges AB = 1, AC = 4, BC = 2, BD = 5, CD = 3.
Kruskal: AB (1) added, BC (2) added, CD (3) added; the tree now has 3 edges , so stop. (AC would form a cycle.)
MST edges: AB, BC, CD with total weight .
Applications: designing least-cost networks, such as electricity, telephone, water and road networks.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 2.5+2.5 marks
Write short notes on (a) Doubly circular linked list (b) Breadth first Search
Answer
(a) Doubly circular linked list
A doubly circular linked list is a linked list in which each node has prev, data and next fields, and the last node's next points to the first node while the first node's prev points to the last. There is no NULL pointer. It can be traversed in both directions starting from any node, and insertion or deletion at either end is if a pointer to the first node is kept. Used in playlists and round-robin scheduling.
struct node { struct node *prev; int data; struct node *next; };
(b) Breadth first search (BFS)
BFS is a graph traversal that visits the start vertex, then all of its neighbours, then their neighbours, level by level. It uses a queue: enqueue the start vertex and mark it visited; repeatedly dequeue a vertex, visit it, and enqueue its unvisited neighbours. Time is . For edges A-B, A-C, B-D, C-D starting at A, the order is A, B, C, D. It finds shortest paths in unweighted graphs.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 2+8 marks
Why do we need sorting? Trace the Quick sort for the input {12, -9, 56, 23, 4, 8, 6, 9, 23, 21}.
Answer
Need for sorting
Sorting arranges data in ascending or descending order. It makes searching much faster (binary search needs sorted data, against ), makes duplicates and ranges easy to find, helps in merging data sets, and presents data in a readable form (reports, ranked lists, directories). Many other algorithms use sorted data.
Quick sort trace (first element as pivot) for {12, -9, 56, 23, 4, 8, 6, 9, 23, 21}
- Pivot 12: smaller [-9, 4, 8, 6, 9], larger or equal [56, 23, 23, 21] gives [-9, 4, 8, 6, 9] 12 [56, 23, 23, 21]
- Left part, pivot -9: -9 [4, 8, 6, 9]
- [4, 8, 6, 9], pivot 4: 4 [8, 6, 9]
- [8, 6, 9], pivot 8: [6] 8 [9]
- Right part [56, 23, 23, 21], pivot 56: [23, 23, 21] 56
- [23, 23, 21], pivot 23: [21] 23 [23]
Combining all parts in order:
-9, 4, 6, 8, 9, 12, 21, 23, 23, 56
Average time is , worst case .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 2+2+6 marks
Define primitive data type with example. What are the advantages of hashing? With your own example show the hash collision and how do you handle it? Explain.
Answer
Primitive data type
A primitive data type is a basic type built into the language, which holds a single value and is not made from other types. Examples in C: int, float, double, char. (Non-primitive types such as arrays, structures and lists are built from these.)
Advantages of hashing
- Insertion, search and deletion in average time.
- Far faster than linear or binary search for large data.
- Needs no sorted data.
- Efficient use in dictionaries, symbol tables, caches and databases.
Hash collision example and handling
Take table size and . Insert 15, 22 and 29: , and . All three keys map to index 1, which is a collision.
1. Separate chaining: each slot keeps a linked list. Index 1 holds 15 → 22 → 29.
2. Linear probing (open addressing): place the key in the next free slot, .
- 15 goes to index 1.
- 22: index 1 full, so it goes to index 2.
- 29: indices 1 and 2 full, so it goes to index 3.
Other open addressing methods are quadratic probing and double hashing. Search follows the same probe sequence until the key or an empty slot is found.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 2+8 marks
Distinguish between static and dynamic list structure. Explain about linked list implementation of stack and queue.
Answer
Static and dynamic list structures
| Basis | Static list (array) | Dynamic list (linked list) |
|---|---|---|
| Size | Fixed at compile time | Grows and shrinks at run time |
| Memory | Contiguous | Non-contiguous, nodes linked by pointers |
| Access | Random access, | Sequential, |
| Insertion or deletion | Needs shifting, | Pointer changes, once position is known |
| Memory use | May waste or overflow | Exact, but extra pointer per node |
Stack using a linked list
Use a singly linked list with a top pointer to the first node; both push and pop happen at the head.
struct node { int data; struct node *next; };
struct node *top = NULL;
- push(x): create a node;
node->next = top; top = node; - pop(): if
top == NULL, underflow; elsetemp = top; top = top->next;freetempand return its data.
Both take and there is no overflow until memory is exhausted.
Queue using a linked list
Keep front (first node) and rear (last node).
- enqueue(x): create a node with
next = NULL; if the queue is empty,front = rear = node; elserear->next = node; rear = node. - dequeue(): if
front == NULL, underflow; elsetemp = front; front = front->next;iffront == NULL, setrear = NULL; freetemp.
Both take . The structure grows dynamically and wastes no memory.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Why do we need circular queue? Explain.
Answer
Need for circular queue
In a simple linear queue implemented with an array of size , deletion advances front and insertion advances rear. Once rear reaches the queue is declared full, even if many slots at the front have been freed by deletions. Space is wasted and the queue cannot be used again unless all elements are shifted or the queue is reset.
A circular queue treats the array as a ring: after the last index, rear and front wrap round to index 0 using
Hence freed slots are reused and the queue is full only when all slots (or , with the usual convention (rear+1) % N == front) are actually occupied.
Example: holding 3 elements at indices 2, 3, 4 with front = 2. A linear queue says "full" at once; a circular queue can still insert at indices 0 and 1.
Advantages: efficient memory use, insertion and deletion, no shifting. Used in CPU scheduling, buffers (keyboard, printer) and traffic systems.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Traverse the following graph using BFS and DFS.
Answer
Consider the graph with vertices A, B, C, D, E, F and edges A–B, A–C, B–D, B–E, C–F, E–F. Neighbours are visited in alphabetical order, and the start vertex is A.
BFS (queue based)
BFS visits all vertices at distance 1, then distance 2, and so on, using a queue.
- Enqueue A and mark it visited. Queue: A.
- Dequeue A, and enqueue its unvisited neighbours B, C. Queue: B, C.
- Dequeue B, and enqueue D, E. Queue: C, D, E.
- Dequeue C, and enqueue F. Queue: D, E, F.
- Dequeue D, E, F. None has unvisited neighbours.
BFS order: A, B, C, D, E, F
DFS (stack or recursion based)
DFS goes as deep as possible along one path before backtracking.
- Visit A, then go to B.
- From B go to D. D is a dead end, so backtrack to B.
- From B go to E, then to F (unvisited neighbour of E).
- From F go to C (unvisited neighbour of F). C's neighbours A and F are already visited, so backtrack until the stack is empty.
DFS order: A, B, D, E, F, C
BFS uses a queue (FIFO) and DFS uses a stack (LIFO). Both run in time when an adjacency list is used.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Explain the insertion and deletion of a node at first and last position of doubly circular linked list.
Answer
In a doubly circular linked list each node has prev, data and next fields. The next of the last node points to the first node, and the prev of the first node points to the last node. Let head point to the first node.
Insertion at the first position
- Create a new node
nwith the given data. - If the list is empty, set
n->next = n,n->prev = nandhead = n. - Otherwise let
last = head->prev.n->next = headn->prev = lastlast->next = nhead->prev = nhead = n
Insertion at the last position
Steps 1 and 2 are the same. Otherwise let last = head->prev.
n->next = headn->prev = lastlast->next = nhead->prev = n
head is not changed. Both insertions take time because the last node is reached through head->prev.
Deletion of the first node
- If the list is empty, report underflow.
- If
head->next == head(one node), free it and sethead = NULL. - Otherwise let
last = head->prevandtemp = head.head = head->nexthead->prev = lastlast->next = head- free
temp
Deletion of the last node
- If the list is empty, report underflow.
- If there is only one node, free it and set
head = NULL. - Otherwise let
last = head->prev.last->prev->next = headhead->prev = last->prev- free
last
All four operations take time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 1+4 marks
Define time and space complexity. Discuss about Round Robin Algorithm for MST.
Answer
Time complexity is the amount of time an algorithm takes as a function of the input size . It is usually expressed with asymptotic notation such as or . Space complexity is the total memory an algorithm needs as a function of , including the input, auxiliary variables and stack space.
Round Robin algorithm for Minimum Spanning Tree
The round robin algorithm (Yao, Cheriton and Tarjan) builds an MST by growing many trees in turn. It uses the cut property: the cheapest edge leaving any tree of the forest belongs to some MST.
- Make each vertex a separate tree. Put all the trees in a queue. Give each tree a priority queue of its incident edges.
- Remove the tree at the front of the queue.
- Find the minimum weight edge leaving . Edges that join two vertices of the same tree are discarded.
- Add to the MST, merge with the tree at the other end of , and merge their edge lists.
- Put the merged tree at the back of the queue.
- Repeat until only one tree remains.
Trees are taken in round robin (queue) order, so every tree gets a turn to grow and small trees are merged first. The result is a spanning tree of minimum total weight. With mergeable heaps the running time is . Kruskal's and Prim's algorithms are .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Traverse the following tree in pre-order and in-order.
Answer
Take the binary tree with root 1, left child 2 and right child 3. Node 2 has children 4 (left) and 5 (right), and node 3 has left child 6.
Pre-order (Root, Left, Right)
Visit the root, then traverse the left subtree, then the right subtree.
1 → 2 → 4 → 5 → 3 → 6
Pre-order: 1, 2, 4, 5, 3, 6
In-order (Left, Root, Right)
Traverse the left subtree, then visit the root, then traverse the right subtree.
4 → 2 → 5 → 1 → 6 → 3
In-order: 4, 2, 5, 1, 6, 3
Recursive form:
void preorder(Node *t){ if(t){ printf("%d ",t->data); preorder(t->left); preorder(t->right);} }
void inorder(Node *t){ if(t){ inorder(t->left); printf("%d ",t->data); inorder(t->right);} }
For a binary search tree, in-order traversal gives the keys in sorted order.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 2+3 marks
Define binary tree and binary search tree. List the applications of Binary tree.
Answer
Binary tree: a tree in which every node has at most two children, called the left child and the right child. It may be empty.
Binary search tree (BST): a binary tree in which, for every node, all keys in the left subtree are smaller than the node's key and all keys in the right subtree are larger. In-order traversal of a BST gives the keys in sorted order.
Applications of binary trees
- Expression trees, used by compilers to parse and evaluate expressions.
- Binary search trees, for fast searching, insertion and deletion.
- Heaps, used for priority queues and heap sort.
- Huffman coding trees for data compression.
- Decision trees and game trees.
- Routing tables and the hierarchical organisation of data.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 2+3 marks
List the limitation of recursion. How do you delete the node in BST?
Answer
Limitations of recursion
- Each call uses stack memory, so deep recursion can cause stack overflow.
- Function call overhead makes recursion slower than an equivalent loop.
- Repeated subproblems may be recomputed, as in naive Fibonacci, giving exponential time.
- It is harder to trace and debug.
- A missing or wrong base case causes infinite recursion.
Deleting a node from a BST
First search for the node with the given key. Then there are three cases.
- Leaf node (no child): remove it by setting the parent's pointer to NULL.
- One child: replace the node by its child. The parent now points to that child.
- Two children: find the in-order successor (the smallest node in the right subtree) or the in-order predecessor (the largest node in the left subtree). Copy its key into the node being deleted. Then delete the successor from the right subtree. The successor has at most one child, so this reduces to case 1 or 2.
Example: deleting 50 from a BST with root 50, left child 30, right child 70, where 70 has left child 60. The successor is 60. Replace 50 by 60 and remove the old node 60.
The time taken is , where is the height of the tree.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 2+3 marks
What is simple queue? Describe about any three types of graphs.
Answer
Simple queue: a linear data structure that follows the FIFO (First In First Out) principle. Insertion (enqueue) takes place at the rear and deletion (dequeue) takes place at the front. It is implemented with an array or linked list using the pointers front and rear. In an array implementation the freed space at the front cannot be reused, which is a drawback.
Types of graphs (any three)
- Undirected graph: the edges have no direction, so edge is the same as . Example: a friendship network.
- Directed graph (digraph): each edge is an ordered pair with a direction from to . Example: web page links.
- Weighted graph: each edge carries a weight such as distance or cost. It is used in shortest path and MST problems.
- Complete graph: every pair of distinct vertices is joined by an edge. It has edges when undirected.
- Cyclic and acyclic graph: a cyclic graph contains a cycle. A directed acyclic graph (DAG) has none.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 2+4+4 marks
Define hash function. Discuss the types of graph. Explain the working mechanism of BFS.
Answer
(a) Hash function
A hash function maps a key to an index of a hash table, , so that the record can be stored and found in near constant time. A common choice is the division method . A good hash function is quick to compute and spreads keys uniformly to reduce collisions. When two keys map to the same index, collisions are resolved by chaining or open addressing.
(b) Types of graph
- Undirected graph: edges have no direction.
- Directed graph: edges are ordered pairs showing direction.
- Weighted graph: edges have weights or costs.
- Complete graph: every pair of vertices is connected.
- Cyclic graph / DAG: a graph that contains a cycle, and a directed graph with no cycle.
- Connected and disconnected graph: whether there is a path between every pair of vertices.
(c) Working of BFS
Breadth First Search traverses a graph level by level from a source vertex, using a queue.
- Mark the source visited and enqueue it.
- While the queue is not empty, dequeue a vertex and process it.
- For each unvisited neighbour of , mark it visited and enqueue it.
- Stop when the queue is empty.
For example, in a graph with edges A–B, A–C, B–D, C–D starting at A, the order is A, B, C, D.
BFS(G, s):
mark s visited; enqueue(Q, s)
while Q not empty:
u = dequeue(Q); visit(u)
for each neighbour v of u:
if v not visited: mark v; enqueue(Q, v)
The time complexity is with an adjacency list. BFS finds the shortest path (fewest edges) in an unweighted graph.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 10 marks
Make a comparison between quick sort and merge sort.
Answer
| Basis | Quick sort | Merge sort |
|---|---|---|
| Method | Divide and conquer. It partitions around a pivot, and the sorting work happens during partitioning. | Divide and conquer. It splits into halves, sorts them recursively and merges. The work happens during merging. |
| Division | Unequal parts, depending on the pivot. | Always two equal halves. |
| Best / average time | ||
| Worst time | , when the pivot is the smallest or largest element, for example on already sorted data with a bad pivot choice. | always. |
| Extra space | for the recursion stack, so it is in-place. | for the auxiliary array. |
| Stability | Not stable. | Stable. |
| Practical speed | Usually faster for arrays, because of good cache use and small constants. | Slightly slower for arrays, but efficient for linked lists and external sorting. |
| Suitable for | Small to medium arrays held in memory. | Large data sets, linked lists and external files. |
| Dependence on input | Depends on pivot selection. | Does not depend on the input order. |
Conclusion: both have average time. Quick sort is in-place and usually faster, but its worst case is and it is not stable. Merge sort guarantees and is stable, but it needs extra memory.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 3+7 marks
What is balanced tree? How do you insert and delete a node in a Binary Search Tree? Explain.
Answer
Balanced tree
A balanced tree is a tree in which the heights of the left and right subtrees of every node differ by a limited amount, for example at most 1 in an AVL tree. This keeps the height at , so search, insertion and deletion take time. Examples are AVL trees and red-black trees. An unbalanced BST can degenerate into a linked list with height .
Insertion in a BST
- 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 and right if it is larger. Duplicates are usually rejected.
- When a NULL position is reached, attach the new node there.
Node* insert(Node* root, int key){
if(root==NULL) return newNode(key);
if(key < root->data) root->left = insert(root->left, key);
else if(key > root->data) root->right = insert(root->right, key);
return root;
}
Inserting 50, 30, 70, 20 gives 50 as root, 30 as its left child, 70 as its right child, and 20 as the left child of 30.
Deletion in a BST
Search for the node, then handle three cases.
- Leaf: remove the node and set the parent's link to NULL.
- One child: link the parent directly to the node's only child and free the node.
- Two children: replace the node's key with its in-order successor (the minimum of the right subtree), or its in-order predecessor. Then delete that successor node from the right subtree. It has at most one child.
Node* delete(Node* root, int key){
if(!root) return NULL;
if(key < root->data) root->left = delete(root->left, key);
else if(key > root->data) root->right = delete(root->right, key);
else {
if(!root->left){ Node* t=root->right; free(root); return t; }
if(!root->right){ Node* t=root->left; free(root); return t; }
Node* s=root->right; while(s->left) s=s->left;
root->data=s->data;
root->right=delete(root->right, s->data);
}
return root;
}
Both operations take time, which is for a balanced tree and in the worst case.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 5 marks
Describe the merits and demerits of sequential search over binary search.
Answer
Merits of sequential search over binary search
- The data need not be sorted. Binary search needs sorted data.
- It is simple to understand and implement.
- It works on linked lists and on any sequential structure. Binary search needs random access, as in arrays.
- It is efficient for small lists and when the item is near the start.
- No time is spent sorting or maintaining order, so it suits data that changes often.
Demerits of sequential search over binary search
- It is slow for large data: comparisons in the worst and average case, against for binary search.
- It does not exploit any ordering of the data.
- For repeated searches on a large static data set it is far less efficient.
For example, in a sorted list of 1,000,000 items, sequential search may need up to 1,000,000 comparisons while binary search needs about 20.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 5 marks
Define level, height and depth of a tree with example.
Answer
Consider a tree with root A. A has children B and C. B has children D and E, and E has child F.
Level: the number of edges (or nodes, by convention) on the path from the root to the node. The root is at level 0 (some books use level 1). Here A is at level 0, B and C at level 1, D and E at level 2, and F at level 3.
Depth of a node: the number of edges on the path from the root to that node. The depth of the root is 0. Here depth(E) = 2 and depth(F) = 3. Depth is the same as level when levels start at 0.
Height of a node: the number of edges on the longest path from the node down to a leaf. Leaves have height 0. Here height(F) = 0, height(E) = 1, height(B) = 2, and height(C) = 0.
Height of the tree: the height of the root. Here the height of the tree is 3, which is the maximum level.
In short, depth and level are counted downward from the root, and height is counted upward from the leaves.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 5 marks
Differentiate between static and dynamic list structure.
Answer
| Basis | Static list | Dynamic list |
|---|---|---|
| Memory allocation | At compile time, with a fixed size, usually an array. | At run time, with memory allocated node by node, as in a linked list. |
| Size | Fixed. It cannot grow or shrink. | Grows and shrinks as needed. |
| Memory use | Can be wasted if the array is not full, and can overflow if it is too small. | Efficient, because only the memory needed is used. |
| Storage | Contiguous memory locations. | Non-contiguous nodes joined by pointers. |
| Access | Direct (random) access by index in . | Sequential access in . |
| Insertion / deletion | Costly, since elements must be shifted, . | Easy, only the pointers change, once the position is known. |
| Extra memory | None. | Extra memory for pointers in each node. |
| Example | Array | Linked list |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 5 marks
How do you insert a node at nth position in singly linked list? Explain.
Answer
To insert a new node at the th position in a singly linked list, traverse to the node at position , then relink.
Steps
- Create a new node
newNodeand store the data in it. - If , insert at the beginning:
newNode->next = head; head = newNode;. - Otherwise set
temp = headand move it forward times, so thattemppoints to the th node. Iftempbecomes NULL, the position is invalid. - Set
newNode->next = temp->next. - Set
temp->next = newNode.
The order of steps 4 and 5 matters. If temp->next is changed first, the rest of the list is lost.
void insertAt(Node **head, int data, int n){
Node *nn = malloc(sizeof(Node)); nn->data = data;
if(n==1){ nn->next=*head; *head=nn; return; }
Node *t=*head;
for(int i=1; i<n-1 && t; i++) t=t->next;
if(!t){ printf("Invalid position"); free(nn); return; }
nn->next=t->next; t->next=nn;
}
Example: for the list 10 → 20 → 40, inserting 30 at position 3 gives 10 → 20 → 30 → 40. The time complexity is .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 5 marks
Differentiate between doubly linked list and doubly circular linked list.
Answer
| Basis | Doubly linked list | Doubly circular linked list |
|---|---|---|
Last node's next | NULL | Points to the first node |
First node's prev | NULL | Points to the last node |
| Traversal | From head to tail or tail to head. It stops at NULL. | It can loop forever, so a stop condition (return to the head) is needed. |
| Access to last node | Needs a traversal or a tail pointer. | Reached in through head->prev. |
| Insertion / deletion at the ends | Must handle NULL links. | No NULL links, so insertion and deletion at either end are uniform and . |
| Any node reachable from any node | Not always, because traversal moves only in two directions up to the ends. | Yes, a full circle is possible from any node. |
| Uses | Navigation, undo/redo. | Round robin scheduling, music playlists, circular buffers. |
Both lists use nodes with prev, data and next fields. The only structural difference is that the circular version links the ends together.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 5 marks
Write a recursive program to generate the Fibonacci series.
Answer
The Fibonacci series is 0, 1, 1, 2, 3, 5, 8, ... defined by , , .
#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, 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 two base cases stop the recursion. This version recomputes values many times, so its time complexity is and its stack depth is . Memoization or an iterative version brings the time down to .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 5 marks
List the advantages and disadvantages of linear queue.
Answer
A linear queue is a FIFO structure in which insertion occurs at the rear and deletion at the front, stored in a linear array.
Advantages
- It is simple to understand and implement.
- Enqueue and dequeue take time.
- It processes elements in arrival order, which is fair. It is useful for scheduling, buffering and BFS.
- It is easy to check whether the queue is empty or full.
Disadvantages
- Memory is wasted. Space freed by dequeued elements at the front cannot be reused, because
rearreaches the end of the array even when space is free at the front. This is false overflow. - The size is fixed in an array implementation, so overflow can occur.
- Only the front can be removed. There is no random access or direct search.
- Reusing space requires shifting elements, which costs , or switching to a circular queue.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 1+4 marks
Define stack. Evaluate + * 3 4 2 using stack.
Answer
Stack: a linear data structure that follows the LIFO (Last In First Out) principle. Insertion (push) and deletion (pop) take place at one end only, called the top.
Evaluation of the prefix expression + * 3 4 2
Scan the expression from right to left. Push operands. For an operator, pop the top as operand 1 and the next as operand 2, compute (operand 1 operator operand 2), and push the result.
| Symbol | Action | Stack (top at right) |
|---|---|---|
| 2 | push | 2 |
| 4 | push | 2, 4 |
| 3 | push | 2, 4, 3 |
| * | 3 * 4 = 12 | 2, 12 |
| + | 12 + 2 = 14 | 14 |
Result: 14
This is the prefix form of .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2083 · 2+3 marks
What is structure? Discuss about time and space complexities.
Answer
Structure
A structure is a user-defined data type that groups variables of different data types under one name. Each variable is a member. It is declared with the struct keyword.
struct Student {
int roll;
char name[30];
float marks;
};
struct Student s1;
Members are accessed with the dot operator, s1.roll. Structures are the basis of records and of nodes in linked lists and trees.
Time complexity
The amount of time an algorithm needs to run, as a function of the input size . It counts the basic operations executed, not seconds. It is expressed in Big-O: constant, logarithmic, linear, , quadratic. Cases are classified as best, average and worst.
Space complexity
The total memory an algorithm needs as a function of . It includes the fixed part (code, constants, simple variables) and the variable part (input, dynamic memory, recursion stack). For example, iterative sum of an array uses extra space, and merge sort uses .
Time and space are often in trade-off, and a good algorithm keeps both low.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BIT 2078 Third Semester Data Structures and Algorithms (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Third Semester Data Structures and Algorithms (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Third Semester Data Structures and Algorithms (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2082 Third Semester Data Structures and Algorithms (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2083 Third Semester Data Structures and Algorithms (TU IOST semester board exam, 2083 (BS), via StudyNp), TU BIT 2078 Third Semester Database Management System (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Third Semester Database Management System (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Third Semester Database Management System (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2082 Third Semester Database Management System (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2083 Third Semester Database Management System (TU IOST semester board exam, 2083 (BS), via StudyNp), TU BIT 2078 Third Semester Numerical Methods (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Third Semester Numerical Methods (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Third Semester Numerical Methods (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2082 Third Semester Numerical Methods (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2083 Third Semester Numerical Methods (TU IOST semester board exam, 2083 (BS), via StudyNp), TU BIT 2078 Third Semester Operating Systems (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Third Semester Operating Systems (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Third Semester Operating Systems (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2082 Third Semester Operating Systems (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2083 Third Semester Operating Systems (TU IOST semester board exam, 2083 (BS), via StudyNp), TU BIT 2078 Third Semester Principles of Management (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Third Semester Principles of Management (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Third Semester Principles of Management (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2082 Third Semester Principles of Management (TU IOST semester board exam, 2082 (BS), via StudyNp) and TU BIT 2083 Third Semester Principles of Management (TU IOST semester board exam, 2083 (BS), via StudyNp). Answers are written for this site; check them against your class notes.