Top Banner Ad
2026-27 Model Paper · Predicted Practice SetSyllabus-aligned practice paper with marking scheme
ACS201 · 2026-27 Model Paper (Set 2)22 Questions

Essentials of Data Structures — 2026-27 Model Paper (Set 2)

Section A

2 Marks Each · 4 questions
Q62MUnit 4 — ML data preprocessing = sorting
Core Concept

Name any two sorting algorithms.

Two common sorting algorithms are Bubble Sort and Quick Sort. Bubble Sort repeatedly swaps adjacent elements if they are in the wrong order, while Quick Sort uses a divide-and-conquer approach by selecting a pivot element to partition the array into smaller sub-arrays, achieving an average time complexity of O(nlog⁡n)O(n \log n).

Key Points

  • Bubble Sort: O(n2)O(n^2) complexity
  • Quick Sort: O(nlog⁡n)O(n \log n) average complexity
  • Sorting is essential for ML data preprocessing
  • Algorithms differ in stability and efficiency
Q72MUnit 5 — Binary tree
Predicted

What is a leaf node in a tree?

A leaf node is a terminal node in a tree data structure that has no children. In a binary tree, a node is a leaf if both its left and right child pointers are NULLNULL. It represents the end of a branch, having a degree of zero.

Key Points

  • Node with no children
  • Degree of zero
  • Terminal node in hierarchy
  • Indicates end of a path
Q1(a)7MUnit 1 — classification (linear / non-linear, static / dynamic)
Core Concept

(a) Explain static and dynamic data structures with examples. Compare arrays and linked lists on memory, access, insertion/deletion, and flexibility.

Concept / Given Data: In computer science, data structures are broadly classified based on their memory allocation strategy into static and dynamic data structures. A static data structure has a fixed memory size allocated at compile time, which cannot be altered during program execution. Conversely, a dynamic data structure can expand or shrink its memory allocation dynamically during run-time using heap memory and pointer references.

Key Formula / Principle: Static Memory: O(1) allocation at compile time,Dynamic Memory: O(n) pointer linking per node\text{Static Memory: } O(1) \text{ allocation at compile time}, \quad \text{Dynamic Memory: } O(n) \text{ pointer linking per node}

Step-by-Step Solution / Detailed Comparison:

  1. Static Data Structures: Memory is allocated contiguously in the stack or static data segment. Once declared, the capacity is unchangeable. The primary example is the one-dimensional or multi-dimensional array in C (intarr[100]int arr[100]). Accessing elements is extremely fast via direct offset calculation.
  2. Dynamic Data Structures: Memory is allocated dynamically during execution using allocation routines like malloc()malloc() or newnew in C/C++, or reference objects in Python. Examples include linked lists, stacks, queues, trees, and graphs. Nodes are linked together via memory pointers.
  3. Comparison Parameters:
    • Memory Allocation: Static allocates fixed contiguous blocks upfront; dynamic allocates memory node-by-node on demand.
    • Access Time: Static structures provide O(1)O(1) random access using index arithmetic. Dynamic structures like linked lists require O(n)O(n) sequential traversal to reach the ii-th node.
    • Insertion and Deletion: In static arrays, insertion or deletion in the middle requires shifting elements, taking O(n)O(n) time. In dynamic linked lists, insertion or deletion at a known pointer location takes O(1)O(1) time.
    • Flexibility: Static structures suffer from potential overflow if limits are exceeded or memory waste if underutilized. Dynamic structures grow and shrink efficiently based on runtime load.

Result: Static structures suit fixed-size datasets requiring fast random access, whereas dynamic structures suit unpredictable, rapidly changing collections.

Tip from Examiner: Clearly tabularize the comparison between arrays and linked lists to score full marks in 7-mark questions.

Key Points

  • Static structures have fixed memory allocated at compile time with O(1) random access.
  • Dynamic structures grow or shrink at runtime using pointers and heap allocation.
  • Arrays provide O(1) indexing but O(n) shifts for middle insertions.
  • Linked lists provide O(1) insertions given a pointer, but O(n) sequential search access.
Q1(b)7MUnit 1 — Array
Core Concept

(b) Write a C or Python program/logic to perform matrix addition and transpose of a 2D array. Explain the steps clearly.

Concept / Given Data: A 2D array represents a matrix of dimensions m×nm \times n, where mm is the number of rows and nn is the number of columns. Matrix addition requires two matrices of identical dimensions, adding corresponding elements: C[i][j]=A[i][j]+B[i][j]C[i][j] = A[i][j] + B[i][j]. Matrix transpose converts rows into columns, such that for an m×nm \times n matrix AA, the transpose TT is an n×mn \times m matrix where T[j][i]=A[i][j]T[j][i] = A[i][j].

Key Formula / Principle: Addition: Ci,j=Ai,j+Bi,j,Transpose: Tj,i=Ai,j\text{Addition: } C_{i,j} = A_{i,j} + B_{i,j}, \quad \text{Transpose: } T_{j,i} = A_{i,j}

Step-by-Step Solution / Program Implementation:

  1. Matrix Addition Logic: Iterate through row index ii from 00 to m−1m-1 and column index jj from 00 to n−1n-1 using nested loops, storing the sum in a resultant matrix.
  2. Matrix Transpose Logic: Iterate through row index ii and column index jj, assigning A[i][j]A[i][j] to T[j][i]T[j][i].
  3. Python Implementation Code:
def matrix_operations():
    # Input matrices A and B
    A = [[1, 2, 3], [4, 5, 6]]
    B = [[7, 8, 9], [10, 11, 12]]
    m, n = len(A), len(A[0])
    
    # 1. Matrix Addition
    C = [[A[i][j] + B[i][j] for j in range(n)] for i in range(m)]
    print('Matrix Addition Result:', C)
    
    # 2. Matrix Transpose of A
    T = [[A[i][j] for i in range(m)] for j in range(n)]
    print('Matrix Transpose Result:', T)

matrix_operations()
  1. Real-World Connect (AI/ML): In machine learning and image processing, grayscale images are handled as 2D NumPy arrays where pixel intensities reside at index A[row][col]A[row][col]. Transposition corresponds to rotating or flipping image axes.

Result: Successfully computed element-wise matrix addition in O(m×n)O(m \times n) time and matrix transposition by swapping row and column indices.

Tip from Examiner: Always check dimension compatibility ($m_1 == m_2$ and $n_1 == n_2$) before performing matrix addition.

Key Points

  • Matrix addition requires identical dimensions and runs in O(m * n) time.
  • Matrix transpose swaps row and column indices: T[j][i] = A[i][j].
  • Nested loops or list comprehensions in Python efficiently implement 2D array traversals.
  • 2D arrays map directly to images, spreadsheet grids, and tensor data in machine learning.

Section B

7 Marks Each · 12 questions
Q12MUnit 1 — classification (linear / non-linear, static / dynamic)
Predicted

Differentiate between linear and non-linear data structures.

Answer: Linear data structure: elements are arranged sequentially, one after another, e.g., array, stack, queue, linked list. (1 mark) Non-linear data structure: elements are arranged hierarchically or as networks, e.g., tree and graph. (1 mark) Result: Linear structures are sequential; non-linear structures represent hierarchical or network relationships.

Key Points

  • Linear: sequential elements such as array, stack, queue (1 mark)
  • Non-linear: hierarchical or network relationships such as tree, graph (1 mark)
Q22MUnit 1 — Data structure
Core Concept

What is Big O notation?

Big OO notation describes an upper bound on the growth of an algorithm’s running time or space requirement as a function of input size nn. It captures the worst‑case asymptotic behaviour, e.g., O(n)O(n), O(logn)O(log n), O(n2)O(n^2).

Key Points

  • Upper bound
  • Asymptotic growth
  • Worst‑case behaviour
  • Examples: O(n)O(n)
Q32MUnit 2 — Singly linked list
Predicted

What is a node in a linked list?

A node is the fundamental building block of a linked list, representing a single element. It consists of two distinct parts: a datadata field to store the actual value and a nextnext pointer field that holds the memory address of the subsequent node in the sequence, forming a logical chain.

Key Points

  • Node contains data and pointer
  • Pointer stores address of next node
  • Last node pointer is NULL
  • Nodes are dynamically allocated
Q42MUnit 3 — Queue
Predicted

State the FIFO principle of a queue.

Answer: FIFO (First In, First Out) means the element inserted first into the queue is the first one removed. Enqueue adds at the rear and dequeue removes from the front. (2 marks) Result: In FIFO, the earliest enqueued element is the first dequeued element.

Key Points

  • FIFO means First In, First Out (2 marks)
  • Enqueue at rear and dequeue from front
Q52MUnit 4 — Linear search
Predicted

Why is binary search faster than linear search on large sorted data?

Answer: Binary search repeatedly halves the search space, giving O(log n) time, while linear search checks elements one by one with O(n) time. For large sorted data, halving needs far fewer comparisons. (2 marks) Result: Binary search is faster because it eliminates half of the sorted data at each step instead of scanning every element.

Key Points

  • Binary search halves search space, O(log n) (2 marks)
  • Linear search checks elements one by one, O(n)
Q17MUnit 1 — Data structure
Predicted

Explain array as a data structure. Discuss insertion, deletion, and traversal operations with their time complexities.

Concept / Given Data

An array is a linear static data structure that stores a collection of elements of the same data type in contiguous memory locations. It allows random access in O(1)O(1) time via indices. However, insertion and deletion in arbitrary positions require shifting elements, leading to a worst-case time complexity of O(n)O(n).

Key Formula / Principle: Address(a[i])=Base Address+(i×Size of Element)\text{Address}(a[i]) = \text{Base Address} + (i \times \text{Size of Element})

Step-by-Step Solution & Working

  1. Traversal: Visiting every element of the array exactly once to process or display data. This requires a single loop running from index 00 to n−1n-1, yielding a time complexity of O(n)O(n).
  2. Insertion: To insert an element XX at a specific index kk in an array of current size nn:
    • Check for overflow (n≥Capacityn \ge \text{Capacity}).
    • Shift all elements from index n−1n-1 down to kk one position to the right: a[j+1]=a[j]a[j+1] = a[j].
    • Insert XX at a[k]a[k] and increment size n=n+1n = n + 1. Time complexity is O(n)O(n) due to shifting.
  3. Deletion: To delete an element from index kk:
    • Check for underflow (n==0n == 0).
    • Shift all elements from index k+1k+1 to n−1n-1 one position to the left: a[j]=a[j+1]a[j] = a[j+1].
    • Decrement size n=n−1n = n - 1. Time complexity is O(n)O(n) due to shifting.
  4. Numerical Trace Example: Consider array [10, 20, 30, 40] of size 44. Inserting 2525 at index 22: elements 40 and 30 shift right to indices 44 and 33 respectively, resulting in [10, 20, 25, 30, 40] with time complexity O(n)O(n).

Result: Arrays provide ultra-fast O(1)O(1) lookup, but modification operations (insert/delete) incur O(n)O(n) overhead when shifting elements.

Tip from Examiner: Clearly state array bounds and shifting direction during insertion and deletion to avoid off-by-one errors and secure full marks.

Key Points

  • Arrays store homogeneous data elements in contiguous memory locations.
  • Traversal visits each element sequentially in O(n)O(n) time.
  • Insertion and deletion require shifting elements, resulting in O(n)O(n) time complexity.
  • Array indexing provides direct random access in O(1)O(1) time.
Q27MUnit 2 — Doubly linked list
Predicted

Explain doubly linked list and circular linked list. Give one application of each.

Doubly and Circular Linked Lists

1. Doubly Linked List (DLL): A DLL is a complex type of linked list where each node contains three fields: data, next (pointer to the successor), and prev (pointer to the predecessor). This bidirectional capability allows traversal in both forward and backward directions.

DLL Node Structure: struct Node{int data; struct Node∗ next; struct Node∗ prev;};struct\ Node \{ int\ data; \ struct\ Node*\ next; \ struct\ Node*\ prev; \};

Application: DLLs are used in browser history management, where the 'Back' and 'Forward' buttons require navigation in both directions. Python's deque also utilizes this structure for efficient insertion and deletion at both ends.

2. Circular Linked List (CLL): A CLL is a variation where the last node does not point to NULL but instead points back to the head node, forming a closed loop. This ensures that the list can be traversed infinitely without reaching a termination point.

CLL Property: last node→next=head;last\ node \rightarrow next = head;

Application: CLLs are ideal for applications requiring cyclic access, such as a music playlist where the player automatically restarts the first song after the last song finishes, or in operating systems for round-robin CPU scheduling.

Comparison Summary:

  • DLL: Bidirectional, requires extra memory for the prev pointer, useful for complex navigation.
  • CLL: Unidirectional (usually), cyclic, useful for continuous processes.

Result: Both structures extend the basic singly linked list to solve specific architectural problems. While DLLs prioritize navigation flexibility, CLLs prioritize continuous, cyclic data processing.

Tip from Examiner: When coding CLLs, be careful to avoid infinite loops during traversal; always check if the current node has returned to the head pointer.

Key Points

  • DLL nodes have prev and next pointers for bidirectional movement.
  • CLL nodes form a loop by pointing the last node to the head.
  • Browser history is a classic application of DLL.
  • Music playlists are a classic application of CLL.
Q37MUnit 3 — implementation using array in C/Python
Predicted

Explain queue operations and their array implementation. Give two real-life applications of queues.

Queue operations. A queue is a FIFO structure with two ends: enqueue inserts at the rear, dequeue removes from the front, front or peek reads the front element without removing it, and isEmpty and isFull report the status. Every operation must check overflow (enqueue on a full array) and underflow (dequeue on an empty queue) before it touches the data.

Array implementation. Keep three variables: front, rear and capacity. Initially both pointers are set to -1.

#define N 5
int q[N], front = -1, rear = -1;
void enqueue(int x) {
    if (rear == N-1) return;          /* overflow */
    if (front == -1) front = 0;
    q[++rear] = x;
}
int dequeue(void) {
    if (front == -1 || front > rear) return -1;  /* underflow */
    return q[front++];
}

A linear array wastes the slots that are freed at the front, so a circular queue uses modulo indexing: rear = (rear+1) % N and front = (front+1) % N, with the full condition detected by (rear+1) % N == front.

Applications. A print spooler holds jobs in arrival order; a CPU scheduler runs processes round-robin; breadth-first search uses a queue to visit graph vertices level by level; call centres and message buffers also queue their requests. In each case fairness depends on serving the oldest request first.

Result: queues use front and rear pointers for FIFO operations, and circular indexing removes the wasted-space problem of a linear array.

Tip from Examiner: State the overflow and underflow conditions explicitly, and draw the circular array with front and rear before and after each operation. Two extra marks are usually reserved for the modulo logic.
Key Formula: Result\text{Result}

Key Points

  • Enqueue at rear, dequeue at front
  • Overflow and underflow checks
  • Front/rear/capacity variables
  • Circular queue avoids wasted slots
  • Applications: spooler, scheduler, BFS
Q47MUnit 4 — Bubble sort and insertion sort
Predicted

Explain insertion sort with algorithm/steps and trace it on [5, 3, 8, 1, 2].

Insertion sort builds a sorted array one element at a time by taking each element and inserting it into its correct position in the already sorted left portion.

Steps: assume the first element is sorted; take the next element as the key; compare the key with the sorted portion from right to left; shift every larger element one position right; insert the key into the gap; repeat until all elements are processed.

for i in range(1, len(a)):
    key = a[i]
    j = i - 1
    while j >= 0 and a[j] > key:
        a[j + 1] = a[j]
        j -= 1
    a[j + 1] = key

Complexity: the best case is O(n)O(n) when the array is already sorted, because only one comparison is needed per element. The average and worst cases are O(n2)O(n^2) because each new key may shift all earlier elements. The algorithm is stable, adaptive and in place, so it suits small or nearly sorted arrays and is used as the base case inside hybrid sorts such as Timsort.

Trace on [5, 3, 8, 1, 2]: pass 1 with key 3 shifts 5 and inserts 3, giving [3, 5, 8, 1, 2]. Pass 2 with key 8 needs no shift, giving [3, 5, 8, 1, 2]. Pass 3 with key 1 shifts 8, 5 and 3 and inserts at the start, giving [1, 3, 5, 8, 2]. Pass 4 with key 2 shifts 8, 5 and 3 and inserts after 1, giving [1, 2, 3, 5, 8].

Result: insertion sort produces the sorted array [1, 2, 3, 5, 8] after four passes.

Tip from Examiner: Draw the array after each pass and mark the sorted prefix clearly. State the best-case $O(n)$ separately from the worst case to secure the complexity mark.
Key Formula: Result\text{Result}

Key Points

  • Insertion sort inserts each key into the sorted prefix
  • Shift larger elements right before inserting
  • Best case O(n)O(n), worst O(n2)O(n^2)
  • Stable, adaptive, in place
  • Trace ends at [1, 2, 3, 5, 8]
Q57MUnit 5 — adjacency list representation
Predicted

Explain graph terminology: vertex, edge, directed graph, undirected graph. Also explain adjacency list representation.

Concept / Given Data

A graph G=(V,E)G = (V, E) is a mathematical structure consisting of a finite set of vertices (nodes) VV and a set of edges EE connecting pairs of vertices. Graphs model relationships in real systems: social networks (users = vertices, friendships = edges), road maps (intersections = vertices, roads = edges), and web pages (pages = vertices, hyperlinks = edges).

Key Terminology:

  1. Vertex (Node): A fundamental unit of the graph. If ∣V∣=n|V| = n, the graph has nn vertices. Example: in a social network, each user is a vertex.

  2. Edge: A connection between two vertices. An edge e=(u,v)e = (u, v) links vertex uu to vertex vv. If ∣E∣=m|E| = m, the graph has mm edges.

  3. Directed Graph (Digraph): Each edge has a direction, written u→vu \rightarrow v. The edge from uu to vv does NOT imply an edge from vv to uu. Example: a "follows" relationship on Twitter — if Alice follows Bob, Bob does not necessarily follow Alice.

  4. Undirected Graph: Edges have no direction; (u,v)(u, v) is the same as (v,u)(v, u). Example: a friendship on Facebook is mutual.

Key Formula / Principle: G=(V,E),∣V∣=n,∣E∣=mG = (V, E), \quad |V| = n, \quad |E| = m

For an undirected graph, each edge contributes to the degree of two vertices: ∑v∈Vdeg⁡(v)=2m\sum_{v \in V} \deg(v) = 2m. For a directed graph, ∑outdeg(v)=∑indeg(v)=m\sum \text{outdeg}(v) = \sum \text{indeg}(v) = m.

Adjacency List Representation:

Instead of an n×nn \times n adjacency matrix (which wastes space for sparse graphs), an adjacency list stores, for each vertex, a linked list (or Python list) of its neighbours.

  • Undirected: for edge (u,v)(u,v), append vv to adj[u]\text{adj}[u] AND append uu to adj[v]\text{adj}[v].
  • Directed: for edge u→vu \rightarrow v, append vv to adj[u]\text{adj}[u] only.

Space complexity: O(n+m)O(n + m) — far better than O(n2)O(n^2) for sparse graphs where m≪n2m \ll n^2.

Worked Example (Undirected, 5 vertices):

Edges: A-B,  A-C,  B-D,  C-EA\text{-}B,\; A\text{-}C,\; B\text{-}D,\; C\text{-}E

Vertex Adjacency List
AA B,  CB,\; C
BB A,  DA,\; D
CC A,  EA,\; E
DD BB
EE CC
graph LR
    A --- B
    A --- C
    B --- D
    C --- E

Step-by-Step Construction (Python dict):

  1. Initialise: adj = {v: [] for v in ['A','B','C','D','E']}
  2. Add edge A-BA\text{-}B: adj['A'].append('B') and adj['B'].append('A')
  3. Add edge A-CA\text{-}C: adj['A'].append('C') and adj['C'].append('A')
  4. Add edge B-DB\text{-}D: adj['B'].append('D') and adj['D'].append('B')
  5. Add edge C-EC\text{-}E: adj['C'].append('E') and adj['E'].append('C')

Result: The adjacency list uses O(n+m)=O(5+4)=O(9)O(n + m) = O(5 + 4) = O(9) space versus O(n2)=O(25)O(n^2) = O(25) for a matrix. For sparse real-world graphs (e.g., a social network with millions of users but relatively few connections per user), adjacency lists are the standard choice.

Tip from Examiner: In 7-mark answers, always (i) define $G=(V,E)$ formally, (ii) give ONE real-world example for directed AND undirected, (iii) show the adjacency list in a table, and (iv) state the space complexity $O(n+m)$. Common mistake: forgetting to add the reverse entry for undirected edges — this loses 1–2 marks. Unit trap: do NOT confuse adjacency list with adjacency matrix; the question specifically asks for the list form.

Key Points

  • Graph G=(V,E): vertices are nodes, edges are connections between them
  • Directed graph: edge u→v is one-way; Undirected: (u,v) = (v,u) mutual
  • Adjacency list stores neighbours per vertex in a list; space O(n+m)
  • Undirected edge adds entry in BOTH lists; directed edge adds in ONE list only
  • Sum of degrees in undirected graph equals 2m (handshaking lemma)
Q2(a)7MUnit 2 — Singly linked list
Core Concept

(a) Explain operations on a singly linked list: insertion at beginning, insertion at end, deletion by value, and traversal.

Operations on a Singly Linked List

A singly linked list is a linear data structure where each node contains a data field and a pointer to the next node. The operations are fundamental to managing dynamic data.

1. Traversal: This involves visiting every node starting from the head until the pointer becomes NULL. We use a temporary pointer temp = head and iterate while(temp != NULL) { print(temp->data); temp = temp->next; }.

2. Insertion at Beginning: To insert a new node at the start, we allocate memory, set new_node->next = head, and update head = new_node. This is an O(1)O(1) operation.

3. Insertion at End: We traverse the list to find the last node where temp->next == NULL. Then, we set temp->next = new_node and new_node->next = NULL. This is an O(n)O(n) operation.

4. Deletion by Value: To delete a node with a specific value, we maintain two pointers: curr and prev. We traverse until curr->data == value. If found, we update prev->next = curr->next and free(curr). If the node is the head, we simply set head = head->next.

Key Principle: TimeComplexityinsert/delete=O(1) (if position is known),O(n) (if searching required)Time Complexity_{insert/delete} = O(1) \text{ (if position is known)}, O(n) \text{ (if searching required)}

Result: These operations allow the linked list to grow or shrink dynamically without the need for contiguous memory allocation, making it highly flexible for applications requiring frequent insertions or deletions.

Tip from Examiner: Always handle the 'empty list' case (head == NULL) before performing deletion or insertion at the end to avoid segmentation faults.

Key Points

  • Traversal visits nodes until NULL pointer.
  • Insertion at head is O(1) as it requires no traversal.
  • Insertion at tail requires O(n) traversal to reach the end.
  • Deletion requires updating the previous node's pointer to skip the target node.
  • Always free memory after deletion to prevent memory leaks.
Q2(b)7MUnit 2 — why linked list over array
Core Concept

(b) Why is a linked list preferred over an array in some situations? Explain with examples of dynamic memory, insertion/deletion cost, and memory utilization.

Linked List vs. Array: Why Linked List is Preferred

While arrays provide O(1)O(1) random access, linked lists are preferred in scenarios requiring dynamic memory management and frequent modifications. The choice depends on the specific requirements of the application.

1. Dynamic Memory Allocation: Arrays have a fixed size determined at compile-time. If the data exceeds this size, the array cannot grow, leading to overflow. Linked lists allocate memory at runtime using malloc(), allowing the structure to grow or shrink as needed.

2. Insertion and Deletion Cost: In an array, inserting or deleting an element in the middle requires shifting all subsequent elements, resulting in O(n)O(n) time complexity. In a linked list, if the position is known, we only update the pointers, which is an O(1)O(1) operation.

Key Principle: Costarray=O(n) (shift),Costlist=O(1) (pointer update)Cost_{array} = O(n) \text{ (shift)}, Cost_{list} = O(1) \text{ (pointer update)}

3. Memory Utilization: Arrays require a contiguous block of memory, which may lead to external fragmentation if a large block is unavailable. Linked lists store nodes in non-contiguous memory locations, utilizing scattered free memory blocks efficiently.

Comparison Summary:

Feature Array Linked List
Size Fixed Dynamic
Memory Contiguous Non-contiguous
Access O(1)O(1) O(n)O(n)
Insert/Delete O(n)O(n) O(1)O(1)

Result: Linked lists are superior when the number of elements is unpredictable or when the application involves frequent insertions and deletions. Arrays remain better for read-heavy applications where index-based access is frequent.

Tip from Examiner: Do not confuse memory efficiency with space complexity. Linked lists use extra space for pointers, so use arrays if memory is extremely tight and size is known.

Key Points

  • Arrays are fixed-size; linked lists are dynamic.
  • Linked lists avoid the O(n) shifting cost during insertion/deletion.
  • Arrays require contiguous memory; linked lists do not.
  • Linked lists have O(n) access time compared to O(1) for arrays.
  • Linked lists use extra memory for storing pointers.

Section C

7 Marks Each · 6 questions
Q3(a)7MUnit 3 — implementation using array in C/Python
Core Concept

(a) Explain stack operations push, pop, peek. Write C/Python logic to implement a stack using an array.

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle, where the last element added is the first one to be removed. The primary operations are: 1. Push: Adds an element to the top of the stack. 2. Pop: Removes and returns the top element. 3. Peek: Returns the top element without removing it.

Concept and Logic: To implement a stack using an array, we maintain a variable toptop initialized to −1-1. The array size MAXMAX defines the capacity. Before pushing, we check for overflow (top==MAX−1top == MAX - 1). Before popping, we check for underflow (top==−1top == -1).

Key Principle: topnew=topold+1 (push),topnew=topold−1 (pop)top_{new} = top_{old} + 1 \text{ (push)}, \quad top_{new} = top_{old} - 1 \text{ (pop)}

C Implementation:

#include <stdio.h>
#define MAX 100
int stack[MAX], top = -1;

void push(int val) {
    if (top == MAX - 1) printf("Overflow\n");
    else stack[++top] = val;
}

int pop() {
    if (top == -1) { printf("Underflow\n"); return -1; }
    return stack[top--];
}

int peek() {
    return (top == -1) ? -1 : stack[top];
}

Step-by-Step Execution:

  1. Initialization: Set top=−1top = -1. The stack is empty.
  2. Push Operation: Increment toptop by 11 and store the element at stack[top]stack[top]. This ensures the most recent element is always at the highest index.
  3. Pop Operation: Access the element at stack[top]stack[top], then decrement toptop by 11. This effectively removes the element from the logical stack.
  4. Peek Operation: Simply return the value at stack[top]stack[top] without modifying the toptop pointer.

Result: The stack provides O(1)O(1) time complexity for all three operations, making it highly efficient for memory management and expression evaluation. The array-based implementation is simple but limited by the fixed MAXMAX size, which can lead to overflow if not managed dynamically.

Tip from Examiner: Always check for underflow before popping and overflow before pushing. Forgetting these boundary conditions is the most common reason for losing marks in practical exams.

Key Points

  • Stack follows LIFO (Last-In-First-Out) order.
  • Push adds to top, Pop removes from top, Peek views top.
  • Array implementation requires a top pointer initialized to -1.
  • Overflow occurs when top equals MAX-1.
  • Underflow occurs when top equals -1.
Q3(b)7MUnit 3 — Stack
Core Concept

(b) What is a balanced parentheses problem? Explain how a stack solves it. Trace the expression {[()()]}.

Concept / Given Data:

The balanced parentheses problem is a classic string-validation problem that determines whether a given sequence of brackets is properly nested and matched. A string is considered balanced if and only if every opening bracket has a corresponding closing bracket of the same type, and they appear in the correct nested order. The three bracket pairs used are ( )(\,), [ ][\,], and { }\{\,\}.

Why a Stack Solves It:

A stack is the ideal data structure because it enforces LIFO (Last In, First Out) order, which mirrors the nesting requirement. The most recently opened bracket must be the first one to close. The algorithm works as follows:

  1. Initialize an empty stack SS with top=−1top = -1.
  2. Scan the input string from left to right, character by character.
  3. If the current character is an opening bracket, push it onto the stack.
  4. If the current character is a closing bracket, check two conditions: (a) the stack must not be empty (underflow means unbalanced), and (b) the popped element must be the matching opening bracket. If either condition fails, return "Unbalanced" immediately.
  5. After the entire string is processed, if the stack is empty, the string is balanced; otherwise, unmatched openers remain and the string is unbalanced.

Step-by-Step Trace for {[()()]}\{[()()]\}:

Step Char Action Stack (bottom → top) Status
1 {\{ push {\{ OK
2 [[ push {\{, [[ OK
3 (( push {\{, [[, (( OK
4 )) pop ((, matches {\{, [[ OK
5 (( push {\{, [[, (( OK
6 )) pop ((, matches {\{, [[ OK
7 ]] pop [[, matches {\{ OK
8 }\} pop {\{, matches empty OK

After all 8 characters are processed, the stack is empty (top=−1top = -1), confirming that the expression {[()()]}\{[()()]\} is balanced.

Result: The expression {[()()]}\{[()()]\} is balanced because every closing bracket correctly matched the most recent unmatched opening bracket, and the stack ended empty with no leftover elements.

Complexity: Time complexity is O(n)O(n) where nn is the string length (single linear pass), and space complexity is O(n)O(n) in the worst case when all characters are openers before any closers appear.

Tip from Examiner: In 7-mark questions, always show the full trace table — examiners award 2 marks for the algorithm description, 3 marks for the step-by-step trace, and 2 marks for the final conclusion with complexity. A common mistake is forgetting to check for underflow (popping from an empty stack) at step 4, which loses 1–2 marks. Always state the final stack state explicitly.
Key Formula: Result\text{Result}

Key Points

  • Balanced parentheses means every opener has a matching closer in correct nested order
  • Stack works because LIFO mirrors nesting: last opened must close first
  • Algorithm: push openers, pop and match on closers, reject on mismatch or underflow
  • Trace of {[()()]}: 8 steps, stack ends empty, result is balanced
  • Time O(n), Space O(n) worst case
  • Always check both underflow AND mismatch at each closing bracket
Q4(a)7MUnit 4 — binary search
Core Concept

(a) Explain binary search algorithm. Write its steps/pseudocode and state its time complexity in best, average, and worst cases.

Concept / Given Data:

Binary search is an efficient divide-and-conquer searching algorithm that works only on a sorted array. It repeatedly divides the search interval in half by comparing the target key with the middle element. If the key equals the middle element, the search succeeds; otherwise, the algorithm discards the half that cannot contain the key and continues on the remaining half.

Precondition: The array a[0..n−1]a[0..n-1] must be sorted in non-decreasing order.

Key Formula / Principle: mid=low+high−low2\text{mid} = \text{low} + \frac{\text{high} - \text{low}}{2}

Step-by-Step Pseudocode:

  1. Set low=0\text{low} = 0 and high=n−1\text{high} = n - 1.
  2. While low≤high\text{low} \leq \text{high}:
    • Compute mid=low+(high−low)/2\text{mid} = \text{low} + (\text{high} - \text{low}) / 2.
    • If a[mid]=keya[\text{mid}] = \text{key}, return mid\text{mid} (found).
    • If a[mid]<keya[\text{mid}] < \text{key}, set low=mid+1\text{low} = \text{mid} + 1 (search right half).
    • Else set high=mid−1\text{high} = \text{mid} - 1 (search left half).
  3. If the loop ends without finding the key, return −1-1 (not found).

Trace Example: Array a=[2,5,8,12,16,23,38,45,56,72]a = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72], key =23= 23.

Step low high mid a[mid]a[\text{mid}] Action
1 0 9 4 16 16<2316 < 23, go right
2 5 9 7 45 45>2345 > 23, go left
3 5 6 5 23 Found at index 5

Time Complexity Analysis:

  • Best case: O(1)O(1) — the key is at the middle element on the first comparison.
  • Average case: O(log⁡2n)O(\log_2 n) — on average, the search space is halved each step.
  • Worst case: O(log⁡2n)O(\log_2 n) — the key is at one of the ends or absent; the algorithm performs at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 comparisons.

The recurrence is T(n)=T(n/2)+O(1)T(n) = T(n/2) + O(1), which by the Master Theorem gives T(n)=O(log⁡n)T(n) = O(\log n).

Binary Search — Halving the RangeStep 1: [0 ........ 9] mid=4Step 2: [5 ........ 9] mid=7Step 3: [5 .. 6] mid=5 ✓Each step halves the search space → O(log n)For n = 1,000,000 → at most 20 comparisons

Result: Binary search reduces the search space exponentially, requiring only O(log⁡2n)O(\log_2 n) comparisons even in the worst case, making it vastly superior to linear search O(n)O(n) for large sorted datasets.

Tip from Examiner: Always state the **precondition** (sorted array) — forgetting it costs 1 mark. Use $\text{mid} = \text{low} + (\text{high}-\text{low})/2$ instead of $(\text{low}+\text{high})/2$ to avoid integer overflow. In the complexity table, write best = $O(1)$, average = $O(\log n)$, worst = $O(\log n)$ — examiners check all three explicitly.

Key Points

  • Binary search requires a sorted array; it halves the search range each step using mid = low + (high-low)/2
  • Best case O(1) when key is at middle; average and worst case both O(log n)
  • Recurrence T(n) = T(n/2) + O(1) solved by Master Theorem gives O(log n)
  • For n = 1,000,000 elements, binary search needs at most 20 comparisons vs 1,000,000 for linear search
  • Use low + (high-low)/2 to prevent integer overflow in C/Java implementations
Q4(b)7MUnit 4 — Merge sort
Core Concept

(b) Explain merge sort using divide and conquer. Trace merge sort on [38, 27, 43, 3, 9, 82, 10].

Concept / Given Data Merge sort follows the divide‑and‑conquer paradigm. It recursively splits an unsorted list into halves until each sub‑list contains a single element (trivially sorted), then merges the sub‑lists to produce a sorted whole. Apply it to the array A=[38,27,43,3,9,82,10]A=[38,27,43,3,9,82,10].

Key Formula / Principle: Merge(L,R):  while L,R not empty, pick smaller front element  append to output\text{Merge}(L,R):\;\text{while }L,R\text{ not empty, pick smaller front element}\;\text{append to output}

Step‑by‑Step Trace

  1. Divide Phase (recursively split):
    • [38,27,43,3,9,82,10][38,27,43,3,9,82,10] → [38,27,43][38,27,43] and [3,9,82,10][3,9,82,10].
    • [38,27,43][38,27,43] → [38][38] and [27,43][27,43].
    • [27,43][27,43] → [27][27] and [43][43].
    • [3,9,82,10][3,9,82,10] → [3,9][3,9] and [82,10][82,10].
    • [3,9][3,9] → [3][3] and [9][9].
    • [82,10][82,10] → [82][82] and [10][10].
  2. Conquer (Merge) Phase – combine pairs:
    • Merge [27][27] and [43][43] → [27,43][27,43].
    • Merge [38][38] with [27,43][27,43] → compare 38 vs 27 → output 27, then 38 vs 43 → output 38, then remaining 43 → [27,38,43][27,38,43].
    • Merge [3][3] and [9][9] → [3,9][3,9].
    • Merge [82][82] and [10][10] → [10,82][10,82].
    • Merge [3,9][3,9] with [10,82][10,82] → [3,9,10,82][3,9,10,82].
    • Final merge of [27,38,43][27,38,43] and [3,9,10,82][3,9,10,82]:
      • Compare 27 vs 3 → output 3.
      • 27 vs 9 → output 9.
      • 27 vs 10 → output 10.
      • 27 vs 82 → output 27.
      • 38 vs 82 → output 38.
      • 43 vs 82 → output 43.
      • Append remaining 82.
    • Sorted array: [3,9,10,27,38,43,82][3,9,10,27,38,43,82].
  3. Complexity
    • Splitting creates log⁡2n\log_2 n levels.
    • Each level merges nn elements → O(nlog⁡n)O(n\log n) total.
    • Space: O(n)O(n) auxiliary array for merging.

Result: Merge sort transforms [38,27,43,3,9,82,10][38,27,43,3,9,82,10] into [3,9,10,27,38,43,82][3,9,10,27,38,43,82] with Θ(nlog⁡n)\Theta(n\log n) time and Θ(n)\Theta(n) extra space.

Tip from Examiner: In marks distribution, allocate points for (i) divide explanation (2 marks), (ii) merge logic with example (3 marks), (iii) final sorted result (1 mark), and (iv) complexity analysis (2 marks). Common error – forgetting to copy remaining elements after one sub‑list empties.

Key Points

  • Merge sort recursively splits until single‑element lists
  • Merging picks the smaller front element from two sorted sub‑lists
  • Time complexity Θ(nlog⁡n)\Theta(n\log n), auxiliary space Θ(n)\Theta(n)
Q5(a)7MUnit 5 — Write inorder and preorder of above BST 3
Core Concept

(a) Define BST. Insert the keys 45, 25, 65, 15, 35, 55, 75 into an empty BST and write inorder, preorder, and postorder traversals.

Concept / Definition:

A Binary Search Tree (BST) is a binary tree in which, for every node NN:

  • All keys in the left subtree of NN are strictly less than NN's key.
  • All keys in the right subtree of NN are strictly greater than NN's key.

This invariant guarantees that an inorder traversal always yields keys in ascending sorted order, making BSTs ideal for database indexing and ordered-set operations.

Key Property: For any node $N$ with key $k$: ∀ x∈LeftSubtree(N):  x<kand∀ y∈RightSubtree(N):  y>k\forall\, x \in \text{LeftSubtree}(N):\; x < k \quad\text{and}\quad \forall\, y \in \text{RightSubtree}(N):\; y > k

Step-by-Step Insertion (keys: 45, 25, 65, 15, 35, 55, 75):

Step Key Comparison Path Placement
1 45 — (empty tree) Root
2 25 25<4525 < 45 → go left Left child of 45
3 65 65>4565 > 45 → go right Right child of 45
4 15 15<4515 < 45 → left; 15<2515 < 25 → left Left child of 25
5 35 35<4535 < 45 → left; 35>2535 > 25 → right Right child of 25
6 55 55>4555 > 45 → right; 55<6555 < 65 → left Left child of 65
7 75 75>4575 > 45 → right; 75>6575 > 65 → right Right child of 65

Resulting Tree Structure:

45 25 65 15 35 55 75

Traversal Traces:

  1. Inorder (Left → Root → Right):

    • Visit left subtree of 45 → inorder of 25's subtree → 15,25,3515, 25, 35
    • Visit root → 4545
    • Visit right subtree of 45 → inorder of 65's subtree → 55,65,7555, 65, 75
    • Result: 15,  25,  35,  45,  55,  65,  7515,\; 25,\; 35,\; 45,\; 55,\; 65,\; 75 ✓ (sorted!)
  2. Preorder (Root → Left → Right):

    • Root 4545 → preorder of left subtree (25,15,3525, 15, 35) → preorder of right subtree (65,55,7565, 55, 75)
    • Result: 45,  25,  15,  35,  65,  55,  7545,\; 25,\; 15,\; 35,\; 65,\; 55,\; 75
  3. Postorder (Left → Right → Root):

    • Postorder of left subtree (15,35,2515, 35, 25) → postorder of right subtree (55,75,6555, 75, 65) → root 4545
    • Result: 15,  35,  25,  55,  75,  65,  4515,\; 35,\; 25,\; 55,\; 75,\; 65,\; 45

Result: The BST is perfectly balanced (height h=2h = 2 edges, 2h+1−1=72^{h+1}-1 = 7 nodes). Inorder confirms the sorted property; preorder gives the insertion order; postorder is useful for deletion (children before parent).

Tip from Examiner: Always verify your inorder is sorted — if it is not, you made an insertion error. For 7-mark questions, draw the tree explicitly (1 mark), show the comparison path for each key (2 marks), and write all three traversals with the rule name stated (3 marks). A common mistake is confusing preorder with postorder; remember: **P**reorder puts **R**oot **F**irst, **P**ostorder puts **R**oot **L**ast.

Key Points

  • BST invariant: left < node < right for every node
  • Inorder traversal of a BST always produces sorted ascending order
  • Preorder = Root, Left, Right; Postorder = Left, Right, Root
  • Insertion follows the BST invariant: compare and go left/right until an empty spot
  • A perfectly balanced BST of height h has 2^(h+1) - 1 nodes
  • Inorder verification is the fastest way to catch insertion errors in exams
Q5(b)7MUnit 5 — Graph
Core Concept

(b) Explain BFS and DFS graph traversals. For the graph A-B, A-C, B-D, B-E, C-F, show BFS and DFS starting from A.

Graph traversal is the process of visiting all vertices in a graph. Breadth-First Search (BFS) and Depth-First Search (DFS) are the two fundamental algorithms used for this purpose.

1. Breadth-First Search (BFS): BFS explores the graph level by level. It starts at a source node and visits all its immediate neighbors before moving to the next level of nodes. It utilizes a FIFO (First-In-First-Out) queue to manage the frontier of nodes to be visited.

2. Depth-First Search (DFS): DFS explores as far as possible along each branch before backtracking. It starts at a source node and dives deep into the graph by visiting a neighbor, then the neighbor's neighbor, and so on. It utilizes a LIFO (Last-In-First-Out) stack or recursion to keep track of the path.

Graph Trace: Given edges: A−B,A−C,B−D,B−E,C−FA-B, A-C, B-D, B-E, C-F.

ABCDEF

BFS Traversal (Queue-based):

  1. Start at AA. Queue: [A][A].
  2. Visit AA, enqueue neighbors B,CB, C. Queue: [B,C][B, C].
  3. Visit BB, enqueue neighbor D,ED, E. Queue: [C,D,E][C, D, E].
  4. Visit CC, enqueue neighbor FF. Queue: [D,E,F][D, E, F].
  5. Visit D,E,FD, E, F. Result: A→B→C→D→E→FA \rightarrow B \rightarrow C \rightarrow D \rightarrow E \rightarrow F.

DFS Traversal (Stack-based):

  1. Start at AA. Stack: [A][A].
  2. Visit AA, push B,CB, C. Stack: [C,B][C, B].
  3. Visit BB, push D,ED, E. Stack: [C,E,D][C, E, D].
  4. Visit DD, pop. Stack: [C,E][C, E].
  5. Visit EE, pop. Stack: [C][C].
  6. Visit CC, push FF. Stack: [F][F].
  7. Visit FF. Result: A→B→D→E→C→FA \rightarrow B \rightarrow D \rightarrow E \rightarrow C \rightarrow F.

Result: BFS visits nodes in order of distance from source, while DFS explores deep paths first. Both have a time complexity of O(V+E)O(V+E) where VV is the number of vertices and EE is the number of edges.

Tip from Examiner: Always maintain a 'visited' set to prevent infinite loops in cyclic graphs. BFS is ideal for shortest path in unweighted graphs, while DFS is better for cycle detection or topological sorting.
Key Formula: Result\text{Result}

Key Points

  • BFS uses a queue for level-order traversal
  • DFS uses a stack or recursion for depth-first exploration
  • Both algorithms have O(V+E)O(V+E) time complexity
  • Visited set is mandatory to avoid cycles
  • BFS finds shortest path in unweighted graphs