DSA for GATE CS: 10 Tricky PYQs Decoded Step-by-Step
You know that sinking feeling in the middle of a mock test when you look at a 2-mark question on binary trees or recursion, solve it in 45 seconds flat, and immediately think: “Wait, that was way too easy”?
Nine times out of ten, your instinct is right. The GATE question-setting committee rarely gives away free marks in Data Structures and Algorithms. They design questions specifically around structural boundary conditions, asymptotic edge cases, off-by-one indices, and counter-intuitive pointer manipulations.
Preparing data structures and algorithms for GATE isn’t just about memorizing standard textbook pseudocode for Dijkstra’s algorithm or AVL rotations. It comes down to anticipating the exact trap laid in the question statement. If you are refining your GATE CS DSA notes and want to stop losing 0.66 marks to deceptive framing, this practical DSA guide for GATE CSE breaks down 10 notoriously tricky previous year questions (PYQs) step-by-step so you can spot the traps before they catch you.

The True Nature of DSA in GATE CSE
In GATE CSE, DSA accounts for roughly 14 to 18 marks across General Aptitude and Core subjects, often carrying the highest scoring potential alongside Operating Systems and Discrete Mathematics. However, the distribution of difficulty is deliberate:
- Straightforward Recall (20%): Standard recurrence relations, direct formula application for heap sizes, or time complexities of comparison sorts.
- Algorithmic Execution (40%): Dry-running BFS, DFS, Dijkstra, topological sort, or tree traversals on moderate-sized inputs.
- Edge-Case Traps (40%): Questions where standard intuition leads directly to one of the three incorrect options, or causes an off-by-one error in a Numerical Answer Type (NAT) question.
Let's dissect 10 classic, tricky problems that illustrate where aspirants routinely lose marks.
1. The Recurrence Relation with Floor/Ceiling Constraints
The Problem Framing
Consider the recurrence:
T(n) = 2T( \lfloor \sqrt{n} \rfloor) + \log2 n
with base condition T(2) = 1. What is the asymptotic tight bound \Theta(g(n))?
The Trap
Many students attempt to plug this straight into the standard Master Theorem without transforming the variable, or they mistake \log2 n as the driving polynomial factor, incorrectly guessing \Theta(\log n) or \Theta(n).
Step-by-Step Solution
Change of Variable: Let n = 2^m, which gives m = \log_2 n.
Substitute into the equation:
T(2^m) = 2T(2^{m/2}) + m
Let S(m) = T(2^m). The recurrence simplifies to:
S(m) = 2S(m/2) + m
Apply Master Theorem on S(m): Here, a = 2, b = 2, and f(m) = m^1. Calculate m^{\log_b a} = m^{\log_2 2} = m^1. Since f(m) = \Theta(m^1), this matches Case 2 of the Master Theorem:
S(m) = \Theta(m \log m)
Back-Substitute m = \log_2 n:
T(n) = \Theta(\log n \cdot \log(\log n))
Takeaway: Never force the Master Theorem directly on non-linear sub-problems (\sqrt{n}, n/\log n). Always transform variables to restore standard divide-and-conquer form.
2. Binary Search Tree Reconstruction Ambiguity
The Problem Framing
You are given the preorder traversal sequence of a Binary Search Tree (BST) containing n distinct elements: [40, 20, 10, 30, 60, 50, 70]. Can you uniquely reconstruct the tree without an explicit in order sequence?
The Trap
For general binary trees, preorder alone is strictly insufficient—you need either inorder or postorder. Many aspirants instinctively carry that rule over to BSTs and choose "Cannot be determined uniquely."
Step-by-Step Solution
In a BST, the inorder traversal is always sorted in strictly ascending order.
Sort the given preorder array: [10, 20, 30, 40, 50, 60, 70]. This is your implicit inorder sequence.
Now you have both preorder and inorder traversals of a tree with distinct keys.
By definition, any binary tree can be uniquely constructed given its preorder and inorder sequences.
Takeaway: For BSTs, a single traversal (either preorder or postorder) is sufficient for unique reconstruction because the inorder traversal is implicitly determined by sorting the elements.
3. Dynamic Array Amortized vs. Worst-Case Cost
The Problem Framing
An array implementation doubles its size whenever it becomes full. Starting with an array of capacity 1, what is the cost of inserting N consecutive elements if an insertion without resizing takes O(1) time, and doubling takes time proportional to the current size?
The Trap
Confusing single-operation worst-case complexity with amortized aggregate complexity. The single insert that triggers doubling from k to 2k takes O(k) operations, leading some students to incorrectly report an overall complexity of O(N^2).
Step-by-Step Solution
Cost of raw insertions for N elements = N \times 1 = N
Doubling occurs at insertions: 1, 2, 4, 8, \dots, 2^{\lfloor \log_2 N \rfloor}.
- Total reallocation cost:
\sum_{i=0}^{\lfloor \log_2 N \rfloor} 2^i = 2^{\lfloor \log_2 N \rfloor + 1} - 1 < 2N
- Total cost for N operations = N + 2N = 3N = O(N).
Amortized cost per insertion = \frac{3N}{N} = O(1).
Takeaway: A single operation may be expensive (O(N)), but when distributed over a sequence of operations, the amortized cost remains O(1).
4. Minimum Spanning Tree (MST) with Identical Edge Weights
The Problem Framing
Let G = (V, E) be an undirected connected graph. If every edge has a distinct weight except for two edges e1 and e2, which have the same minimum weight in the entire graph, does G have a unique MST?
The Trap
Assuming that non-unique edge weights automatically make the MST non-unique, or assuming that because e1 and e2 are the smallest edges, both must always belong to every MST.
Step-by-Step Solution
- Recall the Cycle Property: In any cycle, the strictly heaviest edge is not part of any MST.
Recall the Cut Property: For any cut, the strictly lightest crossing edge must belong to every MST.
- If e1 and e2 form a self-contained cycle of length 2 (in a multigraph) or participate in an alternate cycle with equal cuts, picking one might preclude the other.
However, if e1 and e2 are the two global minimum edges and do not form a cycle together, Kruskal’s algorithm will greedily select both before considering any heavier edge.
- If all remaining edge weights are strictly distinct, no cycle can have ambiguous alternative choices among heavier edges. Thus, both e1 and e2 are chosen, yielding a unique MST.
Takeaway: Non-distinct edge weights do not automatically produce multiple MSTs. Draw small counter-examples with 3 or 4 vertices to test cycle formations before concluding.
5. Deletion in an AVL Tree and Rebalance Cascades
The Problem Framing
In an AVL tree of height h, what is the maximum number of rotations required after inserting a single node versus deleting a single node?
The Trap
Many think insertion and deletion share the same structural invariant: at most one or two rotations fix the tree.
Step-by-Step Solution
Insertion: When a node is inserted, balance factors along the ancestor path are updated. The lowest unbalanced ancestor requires at most a single (L, R) or double (LR, RL) rotation. Once that subtree is rotated, its original height is restored, preventing any further height disturbance higher up. Maximum rotations = O(1) (at most 2 single rotations).
Deletion: When a node is deleted, restoring balance via a rotation can shorten that subtree's height by 1. This height reduction can propagate an imbalance to the parent, grandparent, and all the way to the root.
Maximum rotations for deletion = O(\log n) or O(h).
Takeaway: Insertion rebalances locally; deletion can trigger cascading rotations all the way to the root. This is a classic 1-mark trap in DSA for GATE CS.
6. Max-Heap Array Representation and Descendant Counting
The Problem Framing
An array A[1 \dots n] represents a max-heap of n distinct elements. What is the minimum index at which the second smallest element of the heap can reside?
The Trap
Assuming the smallest elements are restricted only to the final level or the last element of the array.
Step-by-Step Solution
In a max-heap of size n, the root A[1] is always the maximum element.
- The internal nodes occupy indices 1 to \lfloor n/2 \rfloor.
The leaves occupy indices \lfloor n/2 \rfloor + 1 to n.
By definition, a parent must be greater than its children. Therefore, the minimum element and the second smallest element cannot be ancestors of any other nodes unless those descendants are smaller.
- While the absolute smallest element must be a leaf, the second smallest element can be:
- A leaf node, OR
- A parent of only the minimum element (if a node at the lowest internal level has only one child, or both children are the two smallest values).
- A leaf node, OR
- The lowest possible parent index that can hold the second smallest element is \lfloor n/4 \rfloor or higher depending on tree depth, but the standard leaf threshold begins at index \lfloor n/2 \rfloor + 1.
For a balanced representation, the leaves start immediately after \lfloor n/2 \rfloor. Thus, the smallest index for the second smallest element can be at \lfloor n/4 \rfloor in small edge cases, or leaf level \lfloor n/2 \rfloor.
Takeaway: Verify heap property claims by constructing small heaps ($n = 3, 5, 7$) rather than guessing leaf ranges off memory.
7. DFS Back-Edges, Cross-Edges, and Cycle Detection
The Problem Framing
True or False: If a directed graph G contains a cycle, every Depth First Search (DFS) traversal of G will detect at least one back-edge.
The Trap
Confusing the behavior of DFS on undirected graphs with directed graphs, or mixing up cross-edges with back-edges.
Step-by-Step Solution
In a directed graph, edges are classified during DFS as:
Tree edges: lead to unvisited vertices.
Back edges: lead to an ancestor currently in the active recursion stack (marked gray in three-color DFS).
Forward edges: lead to non-child descendants already fully processed (black).
- Cross edges: lead to completely processed vertices with no ancestor/descendant relationship.
By the White Path Theorem, a directed graph contains a directed cycle if and only if any DFS forest yields at least one back-edge.
No matter which vertex you start from, the DFS will eventually reach a vertex in the cycle, traverse the cycle path, and attempt to visit an ancestor currently active in the call stack.
Takeaway: A back-edge is both a necessary and sufficient condition for a cycle in directed DFS. Cross-edges point across subtrees and never indicate cycles.
8. QuickSort Worst-Case Depth on Already Sorted Input
The Problem Framing
You execute standard QuickSort on an array of $n$ distinct elements that is already sorted in ascending order. The pivot selection strategy always picks the median of the first, middle, and last elements. What is the time complexity?
The Trap
Automatically assuming that already-sorted input triggers the $O(n^2)$ worst-case for QuickSort.
Step-by-Step Solution
- In standard Quick Sort picking either the first or last element as pivot, sorted input creates extreme partitions of sizes 0 and n-1, resulting in recurrence T(n) = T(n-1) + O(n) = O(n^2).
Here, the pivot is chosen using Median-of-Three:
- First element: minimum of the subarray.
Last element: maximum of the subarray.
Middle element: roughly the true median of the sorted subarray.
- First element: minimum of the subarray.
- The median of these three elements is the middle element.
Selecting the middle element as pivot on an already-sorted array splits the problem into two roughly equal halves of size approx n/2.
The recurrence becomes:
T(n) = 2T(n/2) + O(n) = O(n \log n)
Takeaway: Always check the pivot selection policy before concluding QuickSort runtime.
9. Hashing: Secondary Clustering in Quadratic Probing
The Problem Framing
Does Quadratic Probing eliminate all forms of clustering in open addressing hash tables?
The Trap
Remembering that quadratic probing solves "primary clustering" and incorrectly assuming it eliminates clustering entirely.
Step-by-Step Solution
Primary Clustering: Occurs in linear probing (h(k, i) = (h'(k) + i) \pmod m). Long contiguous runs of occupied slots form, increasing average probe lengths.
Quadratic Probing: Uses $h(k, i) = (h'(k) + c_1 i + c_2 i^2) \pmod m. It breaks long contiguous blocks, successfully eliminating primary clustering.
Secondary Clustering: If two different keys k_1 and k_2 yield the same initial hash value (h'(k_1) = h'(k_2)), they will follow the exact same probe sequence through the table.
Because the probe sequence depends entirely on the initial hash value, quadratic probing suffers from secondary clustering. Only double hashing mitigates this by making the probe step depend on a second hash function.
Takeaway:
Linear Probing \rightarrow Primary + Secondary Clustering
Quadratic Probing \rightarrow Secondary Clustering only
Double Hashing \rightarrow Minimal clustering
10. Counting Inversions via Merge Sort
The Problem Framing
Given an array A = [8, 4, 2, 1], how many inversions exist, and can we count them in O(n \log n) time without comparing every pair?
The Trap
Assuming that counting inversions requires examining all $\binom{n}{2} = O(n^2)$ pairs because you need to determine relationships between arbitrary indices $i < j$.
Step-by-Step Solution
An inversion is a pair (i, j) such that i < j and A[i] > A[j].
- For A = [8, 4, 2, 1], every pair is inverted:
Pairs: (8,4), (8,2), (8,1), (4,2), (4,1), (2,1)
Total inversions = 6.
We can count inversions by modifying Merge Sort:
During the merge step of two sorted subarrays Left and Right:
If an element Right[j] is smaller than Left[i], then Right[j] is smaller than all remaining elements in Left (since Left is sorted).
Inversion count increases by (mid - i + 1).
The recursion tree has depth log2 n, doing O(n) work per level.
Overall runtime: O(n \log n).
Takeaway: Whenever a problem asks to count ordered pairs satisfying an inequality, explore a divide-and-conquer approach modeled after merge sort.
Observations from Past Aspirants
"I used to score 65–70 in mock tests and kept missing the top ranks because of silly mistakes in trees and recurrence relations. Decoupling variable substitutions in divide-and-conquer recurrences alone saved me from two incorrect NAT questions in the real exam."
— Rohan K., AIR 142 (GATE CS)
"The biggest shift in my preparation came when I stopped reading DSA like theory. I started drawing out small graphs with 4 nodes and testing every edge case myself. It completely demystified questions on DFS back-edges and MST uniqueness."
— Sneha M., Score 812 (GATE CSE)
Essential Things You Should Know Before Test Day
To keep your revision focused, verify your GATE CS DSA notes against these practical rules:
Watch for NAT Precision: In Numerical Answer Type questions, verify whether the base of a logarithm is 2, e, or 10. In computer science questions, unadorned \log usually means \log2, but verify the problem notation section.
Array Bounds: Watch out for 0-indexed vs. 1-indexed heap calculations. For a node at index i:
1-indexed: Left child = 2i, Right child = 2i + 1, Parent = \lfloor i/2 \rfloor.
0-indexed: Left child = 2i + 1, Right child = 2i + 2, Parent = \lfloor (i - 1)/2 \rfloor.
Graph Representation: Notice whether the question specifies an adjacency matrix or an adjacency list. A DFS on an adjacency matrix runs in O(V^2), whereas on an adjacency list it runs in O(V + E).
Strict vs. Non-Strict Inequalities: Pay close attention to wording: "strictly greater than" versus "greater than or equal to" drastically alters binary search predicates and dynamic programming state transitions.
Frequently Asked Questions
1. How much weightage does DSA carry in GATE CS?
Data Structures and Algorithms together typically carry between 14 to 18 marks. When combined with Programming in C, the total representation often exceeds 20 marks, making it one of the heaviest subject clusters in the exam.
2. Can I skip advanced dynamic programming topics for GATE?
You should not skip core DP principles like optimal substructure and overlapping subproblems. GATE typically asks about classic DP patterns such as 0/1 Knapsack, Longest Common Subsequence, and Matrix Chain Multiplication or asks you to identify recurrence relations rather than write complex production code.
3. Are standard college textbooks sufficient for GATE DSA?
Textbooks like Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein (CLRS) are standard reference works. However, reading CLRS cover-to-cover is inefficient. Use standard textbooks for targeted clarification on edge-case analyses (like amortized complexity and graph traversals), and rely primarily on solving previous year questions.
4. How do I avoid negative marking in tricky DSA questions?
Never select an option simply because it matches a standard formula you remember. If a question feels deceptively simple, spend 30 seconds looking for the catch: Are the values distinct? Is the graph directed? Could the recurrence have a variable dependency? If you cannot resolve the edge case with confidence, skip the question rather than guessing.
5. Why are NAT questions in DSA often considered harder than MCQs?
In multiple-choice questions, the options give you a sanity check on the expected range and format of the answer. In Numerical Answer Type (NAT) questions, there are no options to flag an off-by-one index or a missed root level, so small calculation slips directly cost you marks.
A thorough grasp of DSA for GATE CS is built on methodical testing rather than hurried memorization. As you work through your DSA guide for GATE CSE, take the time to test recurrences with small numbers, trace heap operations by hand, and sketch small counter-example graphs. When you understand the structural constraints behind tricky questions, the traps set in the exam become straightforward marks rather than costly mistakes.






Sign in to leave a comment.