Btech 3rd Sem — Data Structures Solved Paper
- Attempt any five questions. All questions carry equal marks (14 each).
- Marks of every part are shown beside the question; answers are written to that length: definition → working/algorithm → example/diagram → conclusion.
- In case of any doubt, the English version of the question is final.
Question-wise topics
| Q.No. | Topics asked |
|---|---|
| Q1 | Traversing a singly linked list; classification of data structures |
| Q2 | Arrays vs linked lists as ADTs; dynamic vs static arrays |
| Q3 | Reverse a stack using one extra stack; circular queue insert/delete |
| Q4 | Push/pop on linked stack; deque and its operations |
| Q5 | Expression tree and traversals; BST creation and deletion |
| Q6 | AVL single and double rotations; DFS vs BFS |
| Q7 | MST and Prim's algorithm; quick sort simulation |
| Q8 | Binary search for 36; short notes: hashing & indexing, heap sort, red-black tree |
Algorithm TRAVERSE(START)
- Set PTR = START.
- Repeat steps 3 and 4 while PTR ≠ NULL:
- Apply PROCESS to PTR→INFO (e.g. print it).
- Set PTR = PTR→NEXT.
- Exit.
void traverse(struct node *start) {
struct node *ptr = start;
while (ptr != NULL) {
printf("%d -> ", ptr->info); /* PROCESS */
ptr = ptr->next;
}
printf("NULL\n");
}Example
| Step | PTR points to | Output so far |
|---|---|---|
| 1 | node 15 | 15 |
| 2 | node 25 | 15 25 |
| 3 | node 35 | 15 25 35 |
| 4 | node 45 | 15 25 35 45 |
| 5 | NULL → stop | 15 25 35 45 |
Counting nodes or summing values uses the same loop (COUNT = COUNT + 1 or SUM = SUM + INFO). Time complexity O(n), extra space O(1).
1. Primitive data structures
Basic types directly supported by the machine/language: int, float, char, double, boolean, pointer. They hold a single value.
2. Non-primitive data structures
Derived from primitive types; they store a collection of values.
- Linear: elements form a sequence; each element has a unique predecessor and successor. Examples: Array (fixed size, contiguous), Linked list (nodes connected by pointers), Stack (LIFO), Queue (FIFO).
- Non-linear: an element may be connected to many others, forming a hierarchy or network. Examples: Tree (hierarchical, e.g. BST, heap), Graph (network of vertices and edges).
Other classifications
- Static vs Dynamic: static size fixed at compile time (array); dynamic size changes at run time (linked list, dynamic array).
- Homogeneous vs Heterogeneous: same type elements (array) vs different types (structure / record).
- Sequential vs Linked storage: contiguous memory (array) vs scattered nodes with pointers (list, tree).
| Linear | Non-linear |
|---|---|
| Data arranged sequentially | Data arranged hierarchically / as a network |
| Single level | Multiple levels |
| Traversed in a single run | Needs special traversals (inorder, BFS, DFS) |
| Array, stack, queue, list | Tree, graph, heap |
Both arrays and linked lists implement the List ADT (ordered collection with operations get(i), insert, delete, search, traverse), but their storage and performance differ.
| Characteristic | Array | Linked list |
|---|---|---|
| Memory allocation | Contiguous block, usually static (compile time) | Non-contiguous nodes, dynamic (run time, malloc) |
| Size | Fixed; must be declared in advance | Grows / shrinks as needed |
| Access to k-th element | Random access O(1): base + k × size | Sequential access O(n) from head |
| Insertion / deletion | O(n) — elements must be shifted | O(1) once the position (pointer) is known |
| Extra memory | None per element (may waste unused slots) | Extra pointer field in every node |
| Search | Linear O(n); binary search O(log n) if sorted | Linear O(n) only (no binary search) |
| Cache locality | Excellent (contiguous) | Poor (scattered nodes) |
| Memory waste | Unused declared slots | Pointer overhead |
| Best suited for | Frequent access by index, fixed-size data, matrices | Frequent insertions/deletions, unknown size, stacks/queues |
int a[100];) and is allocated on the stack or in static memory. A dynamic array is allocated on the heap at run time and can be resized when it becomes full — e.g. C's malloc/realloc, C++ std::vector, Java ArrayList, Python list.How a dynamic array grows
- It keeps three things: pointer to the data block, current size (number of elements) and capacity (allocated slots).
- When size = capacity and a new element is added, a larger block (usually double the capacity) is allocated, old elements are copied and the old block is freed.
- Because doubling happens rarely, appending is amortised O(1) (total copying for n appends ≤ 2n).
int cap = 2, size = 0;
int *a = (int *)malloc(cap * sizeof(int));
void append(int x) {
if (size == cap) { /* full: grow */
cap = cap * 2;
a = (int *)realloc(a, cap * sizeof(int));
}
a[size++] = x;
}
/* ... free(a) when no longer needed */Appending 10, 20, 30, 40, 50: capacity 2 → 4 (at 30) → 8 (at 50).
| Basis | Static array | Dynamic array |
|---|---|---|
| Allocation time | Compile time | Run time (heap) |
| Size | Fixed, cannot change | Can grow or shrink (realloc) |
| Memory management | Automatic (freed when scope ends) | Programmer must free (or garbage collector) |
| Memory usage | May waste space or overflow | Allocates as needed; some spare capacity |
| Flexibility | Low — size must be known in advance | High — size decided by data at run time |
| Access | O(1) random access | O(1) random access (still contiguous) |
| Insertion at end | O(1) until full, then impossible | Amortised O(1); O(n) when resizing |
| Example | int a[50]; | malloc/realloc, vector, ArrayList |
Let S be the given stack with n elements and T an empty auxiliary stack; variables X, I, J. The idea: in round I, take the current top X of S, park the elements below it that are not yet reversed in T, put X down, and bring the parked elements back. After round I, the I lowest positions of S hold the reversed elements.
Algorithm REVERSE(S, n)
- Repeat for I = 1 to n:
- X = POP(S).
- Repeat for J = 1 to n − I: PUSH(T, POP(S)). [move the unreversed elements to T]
- PUSH(S, X). [X goes to its final position]
- Repeat while T is not empty: PUSH(S, POP(T)).
- Exit.
void reverse(Stack *S, int n) {
Stack T; init(&T);
for (int i = 1; i <= n; i++) {
int x = pop(S);
for (int j = 1; j <= n - i; j++)
push(&T, pop(S));
push(S, x);
while (!isEmpty(&T))
push(S, pop(&T));
}
}Trace — S (bottom → top) = 10 20 30 40
| Round | Action | S (bottom → top) after round | T |
|---|---|---|---|
| Start | — | 10 20 30 40 | — |
| i = 1 | x = 40; move 3 element(s) to T, push x, move back | 40 10 20 30 | empty |
| i = 2 | x = 30; move 2 element(s) to T, push x, move back | 40 30 10 20 | empty |
| i = 3 | x = 20; move 1 element(s) to T, push x, move back | 40 30 20 10 | empty |
| i = 4 | x = 10; move 0 element(s) to T, push x, move back | 40 30 20 10 | empty |
- Next position: (i + 1) % MAX.
- Empty: FRONT = −1.
- Full: (REAR + 1) % MAX = FRONT.
Algorithm CQINSERT(Q, MAX, FRONT, REAR, ITEM)
- If (REAR + 1) % MAX = FRONT → print “Overflow” and exit.
- If FRONT = −1 then set FRONT = REAR = 0;
- else set REAR = (REAR + 1) % MAX.
- Q[REAR] = ITEM.
- Exit.
Algorithm CQDELETE(Q, MAX, FRONT, REAR)
- If FRONT = −1 → print “Underflow” and exit.
- ITEM = Q[FRONT].
- If FRONT = REAR then set FRONT = REAR = −1 (queue becomes empty);
- else set FRONT = (FRONT + 1) % MAX.
- Return ITEM.
Example (MAX = 5)
| Operation | Effect | FRONT | REAR | Array |
|---|---|---|---|---|
| Initial | — | −1 | −1 | [ _ _ _ _ _ ] |
| Insert 10 | rear = 0, front = 0 | 0 | 0 | [10 _ _ _ _] |
| Insert 20, 30, 40 | rear = 1, 2, 3 | 0 | 3 | [10 20 30 40 _] |
| Delete | returns 10, front = 1 | 1 | 3 | [ _ 20 30 40 _] |
| Insert 50 | rear = 4 | 1 | 4 | [ _ 20 30 40 50] |
| Insert 60 | rear = (4 + 1) % 5 = 0 — wraps around | 1 | 0 | [60 20 30 40 50] |
| Insert 70 | (0 + 1) % 5 = 1 = front → Overflow | 1 | 0 | full |
In the linked representation each stack element is a node; TOP points to the first node. PUSH and POP are done at the beginning of the list, so both are O(1) and there is no fixed size (overflow only when memory is exhausted).
Algorithm PUSH(TOP, ITEM)
- Allocate a new node NEW; if allocation fails → print “Overflow” and exit.
- NEW→INFO = ITEM.
- NEW→LINK = TOP.
- TOP = NEW.
- Exit.
Algorithm POP(TOP)
- If TOP = NULL → print “Underflow” and exit.
- ITEM = TOP→INFO; TEMP = TOP.
- TOP = TOP→LINK.
- Free TEMP; return ITEM.
- Exit.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *top = NULL;
void push(int x) {
struct node *t = (struct node *)malloc(sizeof(struct node));
if (t == NULL) { printf("Stack Overflow (heap full)\n"); return; }
t->data = x;
t->next = top; /* new node points to old top */
top = t; /* new node becomes top */
}
int pop(void) {
if (top == NULL) { printf("Stack Underflow\n"); return -1; }
struct node *t = top;
int x = t->data;
top = top->next;
free(t);
return x;
}
int main(void) {
push(10); push(20); push(30);
printf("Popped %d\n", pop());
printf("Popped %d\n", pop());
return 0;
}Output: Popped 30, Popped 20.
Types
- Input-restricted deque: insertion only at one end (rear), deletion at both ends.
- Output-restricted deque: deletion only at one end (front), insertion at both ends.
Operations (circular array, MAX size)
| Operation | Algorithm step |
|---|---|
| insertFront(x) | If full → overflow. If empty, front = rear = 0; else front = (front − 1 + MAX) % MAX. Q[front] = x. |
| insertRear(x) | If full → overflow. If empty, front = rear = 0; else rear = (rear + 1) % MAX. Q[rear] = x. |
| deleteFront() | If empty → underflow. x = Q[front]; if front = rear then empty (−1) else front = (front + 1) % MAX. |
| deleteRear() | If empty → underflow. x = Q[rear]; if front = rear then empty (−1) else rear = (rear − 1 + MAX) % MAX. |
| getFront / getRear / isEmpty / isFull | Inspect without changing |
Example
| Operation | Deque (front … rear) |
|---|---|
| insertRear(10) | 10 |
| insertRear(20) | 10 20 |
| insertFront(5) | 5 10 20 |
| insertFront(1) | 1 5 10 20 |
| deleteRear() → 20 | 1 5 10 |
| deleteFront() → 1 | 5 10 |
In an expression tree leaves are operands and internal nodes are operators; each operator node's children are its operands. The operator applied last becomes the root.
- The last operator evaluated is the middle “+” → root.
- Left operand (a + b*c): “+” with children a and (b*c).
- Right operand ((d*e + f)*g): “*” with children (d*e + f) and g; (d*e + f) is “+” with children (d*e) and f.
| Traversal | Order | Result |
|---|---|---|
| Inorder | L N R | a + b * c + d * e + f * g (infix; with brackets: (a + b*c) + ((d*e + f)*g)) |
| Preorder | N L R | + + a * b c * + * d e f g (prefix / Polish) |
| Postorder | L R N | a b c * + d e * f + g * + (postfix / reverse Polish) |
Insertion
| Key | Path compared | Inserted as |
|---|---|---|
| 45 | tree empty | root |
| 26 | 45 | left of 45 |
| 10 | 45 → 26 | left of 26 |
| 60 | 45 | right of 45 |
| 70 | 45 → 60 | right of 60 |
| 30 | 45 → 26 | right of 26 |
| 40 | 45 → 26 → 30 | right of 30 |
Deletion (two-children case uses the inorder successor)
If the inorder predecessor is used instead for 45, the root becomes 40 (largest key in the left subtree) — also correct.
After an insertion/deletion, BF of some node may become +2 or −2; balance is restored by rotations at the nearest unbalanced ancestor A. The four cases depend on where the new node was inserted:
1. LL rotation (single right rotation)
New node inserted in the left subtree of the left child of A. Rotate right at A: the left child B becomes the root of the subtree, A becomes B's right child, and B's old right subtree becomes A's left subtree.
2. RR rotation (single left rotation)
New node inserted in the right subtree of the right child of A. Rotate left at A (mirror of LL).
3. LR rotation (double rotation: left then right)
New node inserted in the right subtree of the left child of A. First left-rotate at the left child B, then right-rotate at A.
4. RL rotation (double rotation: right then left)
New node inserted in the left subtree of the right child of A. First right-rotate at the right child B, then left-rotate at A.
Algorithms
struct node *rightRotate(struct node *A) { /* LL case */
struct node *B = A->left;
A->left = B->right; /* B's right subtree moves to A */
B->right = A;
A->height = 1 + max(h(A->left), h(A->right));
B->height = 1 + max(h(B->left), h(B->right));
return B; /* B is the new subtree root */
}
struct node *leftRotate(struct node *A) { /* RR case */
struct node *B = A->right;
A->right = B->left;
B->left = A;
A->height = 1 + max(h(A->left), h(A->right));
B->height = 1 + max(h(B->left), h(B->right));
return B;
}
/* LR case */ A->left = leftRotate(A->left); A = rightRotate(A);
/* RL case */ A->right = rightRotate(A->right); A = leftRotate(A);| Case | BF(A) | BF(child) | Rotation |
|---|---|---|---|
| LL | +2 | +1 / 0 (left child) | Right at A |
| RR | −2 | −1 / 0 (right child) | Left at A |
| LR | +2 | −1 (left child) | Left at child, right at A |
| RL | −2 | +1 (right child) | Right at child, left at A |
| Basis | BFS (Breadth First Search) | DFS (Depth First Search) |
|---|---|---|
| Strategy | Level by level — all neighbours first | Goes deep along one path, then backtracks |
| Data structure | Queue (FIFO) | Stack (LIFO) / recursion |
| Shortest path | Finds shortest path (fewest edges) in unweighted graphs | Does not guarantee shortest path |
| Memory | Stores a whole level — more memory for wide graphs | Stores one path — less memory (O(height)) |
| Traversal tree | Wide and short | Narrow and deep |
| Time complexity | O(V + E) list / O(V²) matrix | O(V + E) list / O(V²) matrix |
| Backtracking | Not used | Used |
| Applications | Shortest path, peer-to-peer networks, web crawlers, bipartite check, level order | Cycle detection, topological sort, connected components, maze / puzzle solving |
Example (graph A–B, A–C, B–D, B–E, C–F, E–F): BFS from A = A B C D E F; DFS from A = A B D E F C.
Applications: designing least-cost networks (cable, road, electric grid), clustering, approximation of travelling-salesman.
Prim's algorithm
- Start with any vertex s; put it in the tree set T. Set key[s] = 0 and key[v] = ∞ for all other vertices.
- Repeat until T contains all V vertices:
- Among all edges (u, v) with u ∈ T and v ∉ T, choose the edge with minimum weight.
- Add v and the edge (u, v) to the tree.
- Update key[w] = min(key[w], weight(v, w)) for every neighbour w of v not in T.
- Return the V − 1 chosen edges.
Time: O(V²) with an adjacency matrix; O(E log V) with a binary heap (priority queue).
void prim(int G[V][V]) {
int key[V], parent[V], inMST[V];
for (int i = 0; i < V; i++) { key[i] = INF; inMST[i] = 0; }
key[0] = 0; parent[0] = -1;
for (int c = 0; c < V - 1; c++) {
int u = minKey(key, inMST); /* min key vertex not in MST */
inMST[u] = 1;
for (int v = 0; v < V; v++)
if (G[u][v] && !inMST[v] && G[u][v] < key[v]) {
parent[v] = u;
key[v] = G[u][v];
}
}
}Example
| Step | Vertices in tree | Candidate edges | Chosen |
|---|---|---|---|
| 1 | 0 | 0–4(4), 0–1(8) | 0–4 (4) |
| 2 | 0, 4 | 4–2(5), 4–1(6), 4–3(7), 0–1(8) | 4–2 (5) |
| 3 | 0, 4, 2 | 2–1(3), 4–1(6), 4–3(7), 0–1(8), 2–3(9) | 2–1 (3) |
| 4 | 0, 4, 2, 1 | 4–3(7), 2–3(9) | 4–3 (7) |
Partition with the first element as pivot: i moves right while a[i] ≤ pivot, j moves left while a[j] > pivot; swap a[i], a[j] while i < j; finally swap the pivot with a[j]. Recurse on both sides.
int partition(int a[], int lb, int ub) {
int pivot = a[lb], i = lb + 1, j = ub, t;
while (1) {
while (i <= ub && a[i] <= pivot) i++;
while (a[j] > pivot) j--;
if (i < j) { t = a[i]; a[i] = a[j]; a[j] = t; }
else break;
}
t = a[lb]; a[lb] = a[j]; a[j] = t; /* pivot to final place */
return j;
}
void quickSort(int a[], int lb, int ub) {
if (lb < ub) {
int p = partition(a, lb, ub);
quickSort(a, lb, p - 1);
quickSort(a, p + 1, ub);
}
}| Sub-array | Pivot | Swaps | Array after partition (pivot in red) |
|---|---|---|---|
| [0..9] | 55 | swap 72 ↔ 33; swap 88 ↔ 27; j crossed i → swap pivot 55 with 38 | 38331245275588729180 |
| [0..4] | 38 | swap 45 ↔ 27; j crossed i → swap pivot 38 with 27 | 27331238455588729180 |
| [0..2] | 27 | swap 33 ↔ 12; j crossed i → swap pivot 27 with 12 | 12273338455588729180 |
| [6..9] | 88 | swap 91 ↔ 80; j crossed i → swap pivot 88 with 80 | 12273338455580728891 |
| [6..7] | 80 | j crossed i → swap pivot 80 with 72 | 12273338455572808891 |
Pass 1: pivot 55; i stops at 72, j stops at 33 → swap; i stops at 88, j stops at 27 → swap; crossed → swap 55 with 38 → [38, 33, 12, 45, 27, 55, 88, 72, 91, 80].
Binary search needs a sorted list, so first sort it:
51012152123323638568392 (indices 0 … 11)
low = 0; high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) return mid;
else if (key < a[mid]) high = mid - 1;
else low = mid + 1;
}
return -1;| low | high | mid | a[mid] | Decision |
|---|---|---|---|---|
| 0 | 11 | 5 | 23 | 36 > 23 → search right half: low = 6 |
| 6 | 11 | 8 | 38 | 36 < 38 → search left half: high = 7 |
| 6 | 7 | 6 | 32 | 36 > 32 → search right half: low = 7 |
| 7 | 7 | 7 | 36 | Found |
(i) Hashing and Indexing
- Hash functions: division h(k) = k mod m (m prime), mid-square, folding, multiplication.
- Collision: two keys get the same address. Resolution: separate chaining (each slot holds a linked list) or open addressing — linear probing (h + i) mod m, quadratic probing (h + i²) mod m, double hashing (h + i·h₂(k)) mod m.
- Load factor α = n/m; performance degrades as α → 1 for open addressing.
Example: m = 10, keys 23, 43, 13 with h(k) = k mod 10 → all map to 3. Linear probing places them at 3, 4, 5; chaining stores 23 → 43 → 13 in slot 3.
- Primary index: on the ordering key of a sorted file — one entry per block (sparse).
- Secondary index: on a non-ordering field — one entry per record (dense).
- Clustering index: on a non-key ordering field.
- Multilevel index / tree index: an index on the index — implemented by B-trees and B+ trees; search cost O(log n) disk accesses.
- Indexed sequential (ISAM) files: records stored sequentially plus an index for direct access.
Example: a student file sorted by roll number with an index entry for every 100th record — to find roll 457, look up index entry 400 and scan only that block.
(ii) Heap Sort
- BUILD-MAX-HEAP(A): heapify nodes from ⌊n/2⌋ − 1 down to 0 — O(n).
- For i = n − 1 down to 1: swap A[0] ↔ A[i] (largest goes to its final place); reduce heap size by 1; HEAPIFY(A, 0) — O(log n) each.
Example: [4, 10, 3, 5, 1] → build max-heap [10, 5, 3, 4, 1] → swap 10 to end [1, 5, 3, 4 | 10] → heapify [5, 4, 3, 1 | 10] → swap [1, 4, 3 | 5, 10] → heapify [4, 1, 3 | 5, 10] → swap [3, 1 | 4, 5, 10] → [1 | 3, 4, 5, 10] → sorted [1, 3, 4, 5, 10].
Time O(n log n) in best, average and worst case; space O(1) (in-place); not stable.
(iii) Red Black Tree
Height ≤ 2 log₂(n + 1) ⇒ search, insertion, deletion O(log n). Insertion fixes red-red violations by recolouring (uncle red) or rotations (uncle black); it needs at most 2 rotations per insert, which makes it faster to update than an AVL tree. Used in C++ map/set, Java TreeMap, Linux CFS scheduler.