GATE / CS ARCHIVE

SUBJECT COLLECTION

Data Structures

217 questions, newest first

Download PDF with answers Questions-only PDF

Browse topics
Topic weightage, 2017–2026

Average marks per 100-mark paper across the 15 papers of 2017–2026, with how many questions were asked in that time. Compare subjects

  1. Binary Search & Balanced Trees1.313 questions
  2. Heaps & Priority Queues1.110 questions
  3. Stacks & Queues0.87 questions
  4. Hashing0.56 questions
  5. Tree Properties & Traversals0.56 questions
  6. Arrays & Linked Lists0.45 questions
  7. B-Trees & Multiway Search Trees0.22 questions
  8. Other / Mixed Topics0.11 question
Topic frequency by year
Questions by topic and year
Topic199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
Arrays & Linked Lists041212521301111001000000110101011010
Stacks & Queues100201210511140110000101121000111111
Tree Properties & Traversals200121021211031150010104320110100012
Binary Search & Balanced Trees100007320021312001101121312003110123
B-Trees & Multiway Search Trees010200001020100001100000001000000100
Heaps & Priority Queues300001001010111311201001320111102211
Hashing000003000000010010120002200001110012
Graph Representations & Disjoint Sets000000000000000000000000000000000000
Other / Mixed Topics000000000000001000000000100000000010

Show
1 mark · MSQ
Report issue

Leaf indices in a binary heap

Heaps & Priority Queues

Question 23, GATE 2026: A binary minheap contains an odd number n>100 of entries in a 1-indexed array. Which positions are not leaves? A (n+1)/2; B (n−1)/2; C (n−3)/2; D n.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: B, C

Our answer: (n-1)/2 and (n-3)/2

Givens and goal

A binary minheap contains an odd number n>100 of entries in a 1-indexed array. Which positions are not leaves? A (n+1)/2; B (n−1)/2; C (n−3)/2; D n.

Approach

Use the array child-index formula; heap ordering by key value is irrelevant to the tree shape.

Step-by-step solution

1. For a node at position i, its left child would be at 2i and right child at 2i+1. A node is internal if at least the left child exists, which means 2i≤n.
2. Thus internal positions are 1 through floor(n/2); positions floor(n/2)+1 through n are leaves.
3. Write n=2k+1. Then floor(n/2)=k and the proposed positions become A k+1, B k, C k−1, D 2k+1.
4. Positions k and k−1 lie in the internal range. In particular k has children 2k and 2k+1. Positions k+1 and 2k+1 exceed the internal boundary and have no children.
5. Therefore B and C are not leaves. The condition n>100 ensures k−1 is positive and valid; the minheap property affects stored values, not this index boundary.

Original paper, page 18 · Answer key

1 mark · MSQ
Report issue

Linear probing with wraparound

Hashing

Question 24, GATE 2026: An initially empty table has indices 0–10, hash h(x)=(x+7) mod 11, and linear probing. Insert 1,13,22,15,11,24 in that order. Which listed positions are empty: A 0, B 10, C 2, D 1?
Tap to enlarge
Select all that apply
Answer & solution

Official answer: C

Step through it (8 steps)

Givens and goal

An initially empty table has indices 0–10, hash h(x)=(x+7) mod 11, and linear probing. Insert 1,13,22,15,11,24 in that order. Which listed positions are empty: A 0, B 10, C 2, D 1?

Approach

Trace each home slot and each collision in insertion order, wrapping from index 10 to 0.

Step-by-step solution

1. Insert 1: h(1)=8, so place 1 at slot 8. Insert 13: h(13)=20 mod 11=9, so place 13 at 9.
2. Insert 22: h(22)=29 mod 11=7, so place 22 at 7. Insert 15: h(15)=22 mod 11=0, so place 15 at 0.
3. Insert 11: h(11)=18 mod 11=7. Slots 7,8,9 already contain 22,1,13. The first empty slot encountered is 10, so store 11 there.
4. Insert 24: h(24)=31 mod 11=9. Slots 9 and 10 are occupied; probing wraps to 0, which is also occupied. Slot 1 is empty, so place 24 at 1.
5. The final table is:

    index:  0   1   2  3  4  5  6   7   8   9   10
    value: 15  24   -  -  -  -  -  22   1  13   11

6. Of the four listed indices, only 2 is empty. Select C. The probing rule advances from the current candidate slot; it does not recompute a different hash after each collision.

Original paper, page 19 · Answer key

1 mark · NAT
Report issue

Maximum height of a full binary tree

Tree Properties & Traversals

Question 33, GATE 2026: A full binary tree has 23 nodes. Height is the number of edges on its longest root-to-leaf path. Find the largest possible height.
Tap to enlarge
Answer & solution

Official answer: 11

Givens and goal

A full binary tree has 23 nodes. Height is the number of edges on its longest root-to-leaf path. Find the largest possible height.

Approach

Count internal nodes using the full-tree property, then arrange them along one deepest branch.

Step-by-step solution

1. “Full” means every node has either zero children or exactly two children; it does not mean balanced or complete. Let I be the number of internal nodes and L the number of leaves.
2. Every internal node contributes two child edges, so the total edge count is 2I. Any tree with I+L nodes has I+L−1 edges. Equating these gives L=I+1 and total nodes 2I+1.
3. With 23=2I+1, there are I=11 internal nodes and L=12 leaves.
4. A root-to-leaf path of h edges has h nonleaf nodes before the final leaf. All h are internal, so h≤I=11.
5. This bound is achievable by a comb: each of the first ten internal nodes has one leaf child and one internal child continuing the path; the eleventh has two leaf children. There are 11 internal nodes, 12 leaves and a deepest path of 11 edges. Therefore the maximum height is 11, not the roughly logarithmic height of a balanced tree.

Original paper, page 23 · Answer key

2 marks · MCQ
Report issue

Third insertion into a complete BST

Binary Search & Balanced Trees

Question 40, GATE 2026: The keys 1 through 15 are inserted in some order into an ordinary binary search tree, producing a complete binary tree. Which key can never be the third insertion: A 4, B 2, C 10, D 5?
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Givens and goal

The keys 1 through 15 are inserted in some order into an ordinary binary search tree, producing a complete binary tree. Which key can never be the third insertion: A 4, B 2, C 10, D 5?

Approach

Determine the forced final balanced shape and use the rule that each ancestor must be inserted before its descendants.

Step-by-step solution

1. A complete binary tree with 15 nodes has all four levels full. For the ordered keys 1 through 15, the BST invariant therefore fixes root 8, its children 4 and 12, and their children 2, 6, 10 and 14. The leaves are 1, 3, 5, 7, 9, 11, 13 and 15.
2. Ordinary BST insertion without rotations requires every ancestor of a node to have been inserted earlier. Otherwise an earlier inserted descendant would occupy an ancestor position and could not later move below it.
3. The ancestors of 5 are 8, 4 and 6. All three must already exist before 5 is inserted, so 5 cannot be inserted third.
4. Each other offered value can occur third: prefixes (8,12,4), (8,4,2) and (8,12,10) place 4, 2 and 10 third respectively. Each prefix respects the fixed tree's ancestor order, so it can be extended by inserting the remaining keys in an ancestor-before-descendant order to produce the required complete tree.

Common error: A completed tree need not stay complete at every intermediate insertion. Only the final shape is constrained here.

Forced final levels

    depth 0:                8
    depth 1:           4         12
    depth 2:         2   6     10   14
    depth 3:        1 3 5 7   9 11 13 15

Because 15=1+2+4+8 exactly fills four levels, the final complete tree is perfect. Ordinary unbalanced insertion does not move an existing node later, so the ancestor-before-descendant restriction applies to this fixed final shape. Rotations or a self-balancing insertion algorithm are not part of the question.

Original paper, page 29 · Answer key

2 marks · NAT
Report issue

Reconstructing a BST from preorder

Binary Search & Balanced Trees

Question 62, GATE 2026: A binary search tree has preorder sequence 50,25,13,40,30,47,75,60,70,80,77. Find the 1-based position of 60 in its postorder traversal.
Tap to enlarge
Answer & solution

Official answer: 7

Step through it (25 steps)

Givens and goal

A binary search tree has preorder sequence 50,25,13,40,30,47,75,60,70,80,77. Find the 1-based position of 60 in its postorder traversal.

Approach

Recursively split the preorder at each root according to BST value bounds, then traverse left, right, root.

Step-by-step solution

1. The first preorder entry is root 50. The following values below 50 form its left subtree: 25,13,40,30,47. The rest form its right subtree: 75,60,70,80,77.
2. In the left subtree, 25 has left child 13 and right subtree rooted at 40, whose children are 30 and 47. Its postorder is therefore 13,30,47,40,25.
3. In the right subtree, root 75 has a left subtree rooted at 60, containing 70 as 60’s right child. Its right subtree is rooted at 80, with left child 77. Thus that subtree’s postorder is 70,60,77,80,75.
4. The reconstructed tree is:

              50
          /        \
        25          75
       /  \        /  \
     13   40      60   80
         /  \      \  /
        30  47     70 77

5. Concatenate left-subtree postorder, right-subtree postorder and root: 13,30,47,40,25,70,60,77,80,75,50. The first five positions belong to the left subtree, position 6 is 70 and position 7 is 60.
6. Therefore the answer is 7. Preorder visits root first, while postorder visits root last; simply looking up 60’s original preorder position would answer the wrong traversal question.

Original paper, page 45 · Answer key

1 mark · MCQ
Report issue

Recognizing binary-tree traversal order

Tree Properties & Traversals

Question 12, GATE 2026: Match I Inorder, II Preorder, III Postorder to L left-node-right, M node-left-right, N left-right-node. Options: A I-L,II-M,III-N; B I-M,II-L,III-N; C I-N,II-M,III-L; D I-L,II-N,III-M.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Givens and goal

Match I Inorder, II Preorder, III Postorder to L left-node-right, M node-left-right, N left-right-node. Options: A I-L,II-M,III-N; B I-M,II-L,III-N; C I-N,II-M,III-L; D I-L,II-N,III-M.

Approach

Locate the current node relative to its two recursively traversed subtrees.

Step-by-step solution

1. In an inorder traversal the current node is visited between its left and right subtrees: left, node, right. Therefore I matches L.
2. In preorder the current node is visited before either subtree: node, left, right. Hence II matches M. In postorder it is visited after both: left, right, node, so III matches N.
3. For a root r with left leaf l and right leaf t, these orders yield l,r,t; r,l,t; and l,t,r respectively. The same definition applies recursively at every internal node, not only at the root.
4. The combined matching is I-L, II-M, III-N, option A. In a BST, inorder also produces sorted keys, but the traversal definitions themselves apply to all binary trees.

Original paper, page 11 · Answer key

1 mark · NAT
Report issue

Longest chain after hashing

Hashing

Question 30, GATE 2026: Insert keys 5,28,19,15,26,33,12,17,10 into a table with h(k)=k mod 9, resolving collisions by chaining. Find the longest chain length.
Tap to enlarge
Answer & solution

Official answer: 3

Step through it (11 steps)

Givens and goal

Insert keys 5,28,19,15,26,33,12,17,10 into a table with h(k)=k mod 9, resolving collisions by chaining. Find the longest chain length.

Approach

Group all keys by their remainder rather than by insertion adjacency.

Step-by-step solution

1. The nine remainders in order are 5,1,1,6,8,6,3,8,1. For example 28=3×9+1, 33=3×9+6, and 17=1×9+8.
2. Bucket 1 receives 28,19,10; bucket 3 receives 12; bucket 5 receives 5; bucket 6 receives 15,33; bucket 8 receives 26,17. Buckets 0,2,4,7 remain empty.
3. The nonempty chain lengths are therefore 3,1,1,2,2, summing to 9 as a consistency check with the number of inserted keys.
4. The maximum is 3. Whether chaining inserts at the head or tail changes order inside a bucket but not its length. Do not apply linear probing: the problem explicitly stores collisions in chains.

Original paper, page 22 · Answer key

2 marks · MSQ
Report issue

Inserting keys after BST leaves

Binary Search & Balanced Trees

Question 49, GATE 2026: A BST has distinct real keys and n>0 leaves. For each leaf L with an inorder successor, choose one new key k strictly between key(L) and key(successor(L)); collect these in K and insert them. Select: A K has no duplicates; B K is nonempty; C height increases by at most one; D the node count doubles.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A, C

Givens and goal

A BST has distinct real keys and n>0 leaves. For each leaf L with an inorder successor, choose one new key k strictly between key(L) and key(successor(L)); collect these in K and insert them. Select: A K has no duplicates; B K is nonempty; C height increases by at most one; D the node count doubles.

Approach

Use the disjoint sorted gaps associated with leaves and identify each insertion point.

Step-by-step solution

1. The inorder successor is the smallest existing key greater than a given key. Hence each chosen key lies in an open gap between consecutive existing sorted keys. Distinct leaves have distinct, disjoint gaps, so two selected values cannot be equal. This proves A.
2. For a leaf L with a successor, the search for a value in this gap follows the same ancestor comparisons as the search for L. Every ancestor bound is respected because no existing key lies between L and its successor. At L, the new value is larger, and L has no right child, so it is inserted as L’s right child.
3. Gaps belonging to different leaves are disjoint branches of this search structure. Inserting one selected key does not place it on another original leaf’s search path. Consequently each new node becomes a child of its own original leaf, irrespective of insertion order.
4. Every new depth is one more than an old leaf’s depth, so the final height is at most the original height plus one. It may increase by zero when deepest leaves have no insertion, proving C rather than an exact-one claim.
5. A singleton tree has one leaf, its maximum, with no successor. Then K is empty, refuting B and D. A right-only chain gives the same type of counterexample. More generally one inserted key per qualifying leaf does not imply one per original node.
6. Therefore A,C are true. Real-valued keys ensure a value can be chosen in every nonempty open gap.

Original paper, page 35 · Answer key

2 marks · MSQ
Report issue

Reconstructing stack and queue assignments

Stacks & Queues

Question 50, GATE 2026: Items 1,2,3,4,5 arrive in order and are each placed in an initially empty stack S or queue Q (capacity 10 each). After all arrivals, empty S then Q to output 4,3,1,2,5. Possible assignments are A S={1,3,4}; B S={3,4}; C S={4,5}; D S={1,2,3}, with every other item in Q. Select all valid assignments.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A, B

Step through it (4 options)

Givens and goal

Items 1,2,3,4,5 arrive in order and are each placed in an initially empty stack S or queue Q (capacity 10 each). After all arrivals, empty S then Q to output 4,3,1,2,5. Possible assignments are A S={1,3,4}; B S={3,4}; C S={4,5}; D S={1,2,3}, with every other item in Q. Select all valid assignments.

Approach

The stack part reverses its arrival subsequence; the queue part preserves its arrival subsequence.

Step-by-step solution

1. For A, the stack receives 1,3,4 and pops 4,3,1. The queue receives 2,5 and dequeues 2,5. Concatenating the two outputs gives 4,3,1,2,5, so A works.
2. For B, the stack receives 3,4 and pops 4,3. The queue receives 1,2,5 and outputs 1,2,5. The same target output results, so B also works.
3. For C, the stack pops 5,4 and the queue outputs 1,2,3, producing 5,4,1,2,3. For D, the stack pops 3,2,1 and the queue outputs 4,5, producing 3,2,1,4,5. Both differ from the target.
4. Thus select A,B. The stack prefix must be decreasing and the queue suffix increasing, but the split point is not uniquely determined: here it can be after 4,3 or after 4,3,1. No interleaved dequeue or pop is permitted before all arrivals.

Original paper, page 36 · Answer key

1 mark · MSQ
Report issue

Distinguishing BST guarantees from worst-case bounds

Binary Search & Balanced Trees

Question 26, GATE 2025: For a BST storing n distinct integers, assess: A “The maximum length of a path from the root node to any other node is (n−1).” B inorder traversal is always sorted. C worst-case search takes O(log₂ n). D every BST is a Min-Heap. Select all true statements. A’s wording is retained because it has a material quantifier ambiguity.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A, B

Our answer: A;B under upper-bound interpretation; B under literal per-tree equality

Approach: Separate guarantees for every individual tree from the largest possible height among all n-node BSTs.
Inorder traversal visits the left subtree, root, then right subtree. By the BST ordering invariant all left keys are smaller and all right keys are larger. Applying that reasoning recursively produces sorted order, so B is unconditionally true.
Any root-to-node path contains at most n nodes, hence at most n−1 edges. A completely skewed BST attains this bound. Under the intended “maximum possible over all BSTs” interpretation, A is true and the official answer is A,B. Literally, however, A says that each tree’s maximum root path IS n−1. A balanced three-node BST has height 1 rather than 2, so under that reading A is false and only B survives.
C is false because search follows a root-to-node path and may take Θ(n) in a skewed BST; balancing is not promised. D is false because a BST need not be complete, and its left child can be smaller than its root, violating min-heap order.
Keep the official A;B for scoring while explicitly warning about A’s wording. The mathematical distinction must not be hidden by replacing “is” with “at most”.

Original paper, page 26 · Answer key

1 mark · NAT
Report issue

Computing the height of a binary heap

Heaps & Priority Queues

Question 35, GATE 2025: Height is the largest number of edges on a root-to-leaf path. A Min-Heap stores 32 keys. Under the standard binary-heap convention, what is its height?
Tap to enlarge
Answer & solution

Official answer: 5

Approach: Use the complete-binary-tree shape of a binary heap; key order does not determine its height.
At depth d, a binary tree can contain at most 2d nodes. The completely filled levels from depth 0 through depth 4 contain 1+2+4+8+16=31 nodes. A 32nd node therefore cannot fit in those levels and must occupy depth 5.
A heap is complete: all levels except possibly the last are full, with the last filled from left to right. Hence 32 keys create one node at depth 5 and none deeper. The height, measured in edges, is 5.
Equivalently, an n-node complete binary tree has height floor(log₂ n), and floor(log₂32)=5. Counting occupied levels would give 6, but the question explicitly uses edges. The answer relies on the conventional binary meaning of Min-Heap; arbitrary heap-ordered trees need not have this shape.

Original paper, page 35 · Answer key

2 marks · NAT
Report issue

Tracing successor deletion in a linked list

Arrays & Linked Lists

Question 62, GATE 2025: L1 is 1→7→12→3→9→5→11→15→8→NULL and L2 is 1→11→6→9→15→12→4→NULL. find(q,L2) returns whether q occurs in L2. Starting ptr1=L1, repeat while ptr1->next!=NULL: set query=ptr1->next->data; if find(query,L2), execute ptr1->next=ptr1->next->next; otherwise advance ptr1=ptr1->next. How many nodes remain reachable in L1?
Tap to enlarge
Answer & solution

Official answer: 5

Approach: Notice that the tested node is ptr1’s successor, not ptr1 itself. On deletion the pointer stays still, so the replacement successor is tested next.
Initially ptr1 points to the head value 1. Its successor 7 is not in L2, so advance to 7. The next value 12 is in L2, so bypass it, leaving 7 pointing to 3. Keep ptr1 at 7, test 3, and then advance to 3 because it is absent from L2.
Delete successor 9, retain and advance to 5, then delete 11 and 15 in consecutive iterations while ptr1 remains at 5. Finally retain 8 and stop because its next pointer is NULL.
The resulting list is 1→7→3→5→8, so five nodes remain. Although head value 1 also occurs in L2, it is never tested as a successor and is not removed. Advancing ptr1 after a deletion would incorrectly skip a candidate such as 15. The code unlinks nodes without calling free; the question asks reachability in L1, not the count of still-allocated memory objects.

Original paper, page 62 · Answer key

2 marks · NAT
Report issue

Tracing double-hash probing positions

Hashing

Question 65, GATE 2025: An initially empty hash table has m=11 slots. h1(k)=k mod 11, h2(k)=1+(k mod 7), and probe i uses [h1(k)+i·h2(k)] mod 11, starting at i=0. Insert 63,50,25,79,67,24 in that order. In which slot does 24 end up? The formula yields a zero-based index; the official range also accepts the corresponding one-based slot number.
Tap to enlarge
Answer & solution

Official answer: 10 to 11

Our answer: 10

Step through it (8 steps)

Approach: Insert the earlier keys first, because their occupied positions determine how many probes key 24 needs.
For the first five keys the primary hash locations are 63 mod 11=8, 50 mod 11=6, 25 mod 11=3, 79 mod 11=2 and 67 mod 11=1. All differ, so each key is placed on its first probe. Occupied indices are therefore {1,2,3,6,8}.
For 24, h1=24 mod 11=2 and h2=1+(24 mod 7)=1+3=4. Probe i=0 checks index 2, occupied by 79. Probe i=1 checks (2+4) mod 11=6, occupied by 50. Probe i=2 checks (2+8) mod 11=10, which is empty, so 24 is stored there.
The derived index is 10. This is the eleventh slot if slots are described with one-based ordinal numbers. Preserve the official accepted interval 10–11, but use 10 when interpreting the given modulo formula literally. The second hash is the step size, not a replacement initial index.

Original paper, page 64 · Answer key

1 mark · MCQ
Report issue

Tree Properties & Traversals

Question 13, GATE 2025: A nonempty binary tree has n nodes, and every node has either zero or exactly two children. How many nodes have two children?
Options: A. (n−2)/2; B. (n−1)/2; C. n/2; D. (n+1)/2.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Let i be the number of internal nodes and l the number of leaves, so n=i+l. Count the tree edges in two ways. Every non-root node has exactly one parent, giving n−1 edges in total. On the other hand, each internal node contributes two parent-to-child edges and each leaf contributes none, giving 2i edges. Therefore 2i=n−1 and i=(n−1)/2.

This also implies l=i+1=(n+1)/2, which explains why D is a plausible but incorrect distractor: it counts leaves. Such a tree has odd n, as n=2i+1. At the boundary n=1, the root is a leaf and the formula gives zero two-child nodes, as required. This is a full/proper binary tree property; it does not require the tree to be balanced or all leaves to be at the same depth. Answer: B.

Original paper, page 12 · Answer key

1 mark · NAT
Report issue

Binary Search & Balanced Trees

Question 35, GATE 2025: Insert 10,−4,15,30,20,5,60,19 in that order into an initially empty ordinary binary search tree, with no balancing rotations. How many edges are on the path from node 19 to the root?
Tap to enlarge
Answer & solution

Official answer: 4

Step through it (10 steps)

Insert by comparing each new key with the nodes on its search path. The first key 10 becomes the root. −4 is its left child and 15 its right child. Next 30 becomes the right child of 15; 20 becomes the left child of 30. The key 5 goes right of −4, and 60 goes right of 30.

For 19, compare with 10: go right. Compare with 15: go right. Compare with 30: go left. Compare with 20: go left and insert there. Thus its root path is 10→15→30→20→19.

There are five nodes on that path but four edges, so the requested distance is 4. This is its depth when the root has depth zero. The left branch containing −4 and 5, and the right branch containing 60, do not contribute to this path. Answer: 4.

Original paper, page 26 · Answer key

2 marks · MCQ
Report issue

Other / Mixed Topics

Question 38, GATE 2025: Meld combines two size-n instances into one of the same data structure. Let P be an unsorted doubly linked list with head and tail pointers, Q an array-based min-heap, and R a binary search tree. Choose the best worst-case time complexities.
A. P Θ(1), Q Θ(n), R Θ(n).
B. P Θ(1), Q Θ(n log n), R Θ(n).
C. P Θ(n), Q Θ(n log n), R Θ(n²).
D. P Θ(1), Q Θ(n), R Θ(n log n).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

P: join the first list's tail to the second list's head, set the corresponding previous pointer, and choose the resulting head and tail. Only a constant number of pointer changes are needed, with separate constant-time handling of empty lists. The list is unsorted, so no ordering merge is required: Θ(1).

Q: place both arrays into one 2n-element array and apply bottom-up build-heap. Build-heap is linear, not Θ(n log n): there are many nodes near leaves that require only short sift-down operations, and summing their heights gives O(n). The concatenation/output work is also linear, so Θ(n) suffices. Inserting each item separately is valid but needlessly slower in the worst case.

R: perform inorder traversals to get two sorted sequences in Θ(n), merge them in Θ(n), and build a balanced BST from the merged sequence by choosing midpoints recursively in Θ(n). Arbitrarily interleaved key sets require linear worst-case work/comparisons to establish their joint ordering, so the meld bound is Θ(n), rather than the cost of repeated naive insertions into a possibly skewed tree.

The three bounds are Θ(1),Θ(n),Θ(n): A.

Original paper, page 29 · Answer key

2 marks · MSQ
Report issue

Stacks & Queues

Question 45, GATE 2025: A stack stores records with distinct positive integer keys. Add MIN, which returns a pointer to the minimum-key record without removing it, in O(1) time while keeping PUSH and POP O(1). Which proposed augmentations suffice?
A. Every record stores a pointer to the smallest-key record below it.
B. Store only one pointer to the current minimum record.
C. Maintain an auxiliary sorted array of all present keys.
D. Maintain a min-heap of all present keys.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A

A preserves the minimum of every stack prefix, which is the information needed after future pops. For an empty stack use a null pointer. When pushing a new record r onto old top t, compare t.key with the key at t's saved below-minimum pointer, if present. The smaller of those records is the minimum of the entire old stack, so store its pointer in r. This takes O(1). MIN compares the current top with its saved below-minimum and returns the smaller. POP simply exposes the previous top, whose saved pointer is still valid because stack deletion has removed nothing below it. Thus all three operations remain O(1).

B alone supports a new minimum on PUSH but loses the information needed when POP removes the current minimum. Finding the next minimum can require scanning the remaining stack. C permits constant-time access to the smallest sorted entry, but inserting an arbitrary new key can require Θ(n) shifts. D exposes its minimum in O(1), but maintaining the heap on insertions and deletions costs O(log n), not O(1) worst case. Those structures do not meet all requirements merely because their MIN operation is fast. Select A only.

Original paper, page 34 · Answer key

1 mark · MCQ
Report issue

Root exception to B+ tree occupancy

B-Trees & Multiway Search Trees

Question 21, GATE 2024: In a B+ tree, which nodes are exempt from the general requirement of at least 50% occupancy? A Only the root; B all leaves; C all internal nodes; D only the leftmost leaf.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Approach: Separate the root's special role from the minimum-occupancy rules for ordinary nodes.
1. A B+ tree keeps nonroot nodes sufficiently full so that the number of nodes, and hence the height and search cost, stay controlled. Splitting, redistribution and merging maintain these lower bounds after updates.
2. The root needs an exception. If the entire tree fits in one leaf, that root leaf can contain only a few records. If the root is internal, it may have just two children even when the ordinary minimum for an internal node is larger.
3. Giving all leaves or all internal nodes the same exemption would abandon the normal occupancy guarantee. Being the leftmost leaf does not create an exception either.
Answer: A. Precise key-versus-child counts depend on the chosen order convention, but the special status of the root does not.

Original paper, page 15 · Answer key

2 marks · MCQ
Report issue

Heapify into a max-heap

Heaps & Priority Queues

Question 41, GATE 2024: The array [82,101,90,11,111,75,33,131,44,93] is “heapified”. Which first three entries result? A 82,90,101; B 82,11,93; C 131,11,93; D 131,111,90. The original does not specify min-heap versus max-heap; the official answer uses the usual bottom-up max-heap interpretation.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Step through it (13 steps)

Approach: Under the intended max-heap convention, every parent must be at least as large as its children. Build the heap bottom-up by sifting down internal nodes, using zero-based indices.
1. Start at index 4 (value 111), whose child is 93, so no change. At index 3, swap 11 with its larger child 131. Index 2 contains 90 above children 75 and 33 and needs no change.
2. At index 1, 101 has children 131 and 111. Swap with 131; 101 then sits at index 3 above 11 and 44.
3. At index 0, 82 must move below 131. At its new index 1, move it below 111; then at index 4 move it below 93.
4. The resulting array is [131,111,90,101,93,75,33,11,44,82]. Its first three entries are 131,111,90, matching D.
“Heap” alone also allows a min-heap, whose root would be 11, absent from all options. The question also does not name a particular construction algorithm. D is retained as the official intended answer, not as a uniquely forced result of the literal wording. Existing discrepancy CS-2024-S1-Q41-HEAP-TYPE remains open.

Original paper, page 26 · Answer key

2 marks · MCQ
Report issue

Locate the largest key in a min-heap

Heaps & Priority Queues

Question 43, GATE 2024: A binary min-heap contains 105 distinct elements. If k is the array index holding the maximum element, how many values can k take over valid heaps? A 53; B 52; C 27; D 1.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Approach: Use the heap-order property to restrict the maximum to leaves, then count leaves in the complete binary-tree shape.
1. In a min-heap every parent is smaller than its children because all keys are distinct. If the maximum were an internal node, its child would need to be still larger, a contradiction. Thus the maximum must be a leaf.
2. With one-based indexing, internal nodes are indices 1 through floor(105/2)=52. Leaves occupy indices 53 through 105, giving 105−52=53 leaves.
3. Every leaf is a feasible maximum location: place the largest key at the chosen leaf and assign the remaining keys in increasing order along a parent-before-child ordering of the remaining nodes. All parent-child inequalities can be satisfied.
Answer: A, 53. Zero-based indexing changes the leaf indices to 52 through 104 but not their number. The maximum is not fixed at the last array position; any leaf can hold it.

Original paper, page 27 · Answer key

2 marks · MCQ
Report issue

What a BST reveals without its insertion order

Binary Search & Balanced Trees

Question 39, GATE 2024: A BST is built by inserting distinct integers from a known set V into an empty tree, with smaller keys in each left subtree. The insertion order and tree are unknown. What can always be determined from V? A inorder traversal; B root; C preorder; D postorder.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Approach: Use the BST order invariant and test the other traversals on two possible insertion sequences.

1. Derivation. An inorder traversal of a BST with distinct keys and smaller keys to the left always visits exactly the sorted set V, regardless of insertion order. The first inserted key becomes the root, and different insertion orders can change the root, preorder, and postorder. Hence only inorder is determined in general, option A. Trivial sets can coincidentally determine more, but do not establish those claims for arbitrary V.

2. Explanation and checks. For V={1,2,3}, inserting 2,1,3 gives root 2, preorder 2,1,3 and postorder 1,3,2. Inserting 1,2,3 gives root 1, preorder 1,2,3 and postorder 3,2,1. Both have inorder 1,2,3. Recursively, inorder visits smaller values, then the node, then larger values; thus it is the sorted list for every valid shape. The examples demonstrate why knowledge of the set alone cannot recover the shape-sensitive alternatives.

Original paper, page 26 · Answer key

2 marks · MSQ
Report issue

Generate output through two bounded stacks

Stacks & Queues

Question 48, GATE 2024: S1 has capacity 4 and initially contains bottom-to-top 100,200,300,400. S2 has capacity 2 and is empty. T pops S1 into S2; R pops S2 into S1; O pops S1 to output. Empty pops and full pushes are forbidden. Which output orders are possible? A 100,200,400,300; B 200,300,400,100; C 400,200,100,300; D 300,200,400,100.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: B, C, D

Step through it (4 options)

Approach: Give legal operation witnesses for possible orders and a storage lower bound for the impossible order.

1. Derivation. Write T for PushToS2, R for PushToS1, and O for GenerateOutput. Starting with S1 bottom-to-top100, 200, 300, 400 and empty S2: B is realized by T, T, O, R, O, R, O, O; C by O, T, O, O, R, O; D by T, O, O, R, O, O. These produce the stated sequences without exceeding S2 capacity 2. A cannot start with 100: reaching it before any output requires all three higher elements outside S1, but S2 holds only two. Thus B, C, D.

2. Explanation and checks. For B, the first two T operations park 400 then 300 in S2, exposing 200. Output 200, restore and output 300, restore and output 400, then output 100. For C, output 400 first and park only 300; this exposes both 200 and 100 before restoring 300. For D, park only 400 and output 300,200 before restoring it. No hidden extra buffer is available, which is why starting with 100 is impossible.

Original paper, page 33 · Answer key

1 mark · MCQ
Report issue

Heaps & Priority Queues

Question 12, GATE 2023: Which 1-indexed array is a max-heap? A [23,17,10,6,13,14,1,5,7,12]; B [23,17,14,7,13,10,1,5,6,12]; C [23,17,14,6,13,10,1,5,7,15]; D [23,14,17,1,10,13,16,12,7,5].
Tap to enlarge
Your answer
Answer & solution

Official answer: B

In a one-indexed max-heap, A[i] must be at least both A[2i] and A[2i+1] when those children exist. B satisfies all parent-child inequalities: 23≥17, 14; 17≥7, 13; 14≥10, 1; 7≥5, 6; 13≥12. A fails at 10<14, C at 6<7 and 13<15, and D at 1<12. Answer B.

Teaching detail. A heap is only partially ordered: parent keys dominate child keys, but siblings need not be sorted and the array need not be globally descending. There are only five possible parent positions in this ten-element array. For A, index 3 contains 10 and child index 6 contains 14. For C, parent index 4 contains 6 but child 9 contains 7. For D, parent 4 contains 1 but child 8 contains 12. One violation suffices to reject a candidate; every edge must pass to accept B.

Original paper, page 9 · Answer key

1 mark · MCQ
Report issue

Arrays & Linked Lists

Question 13, GATE 2023: Given pointers to a list's head and an arbitrary node to delete, compare worst-case deletion time for singly and doubly linked lists of n nodes. A O(1),O(n); B O(log n),O(log n); C O(1),O(1); D O(n),O(1).
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Deleting an arbitrary node of a singly linked list requires locating its predecessor to reconnect the list. In the worst case the target is the tail and this takes a traversal, Θ(n); copying the next node’s value is not a universal solution for the tail. A doubly linked node directly exposes its predecessor and successor, so a constant number of links and possibly the head pointer suffice, Θ(1). Answer D.

Teaching detail. The important missing link in a singly linked node is its predecessor. Knowing the head and the target does not provide that predecessor directly, and freeing the target without redirecting its predecessor would leave a dangling link. For a doubly linked node u, set u.prev.next=u.next and u.next.prev=u.prev when those neighbors exist; handle a head or tail by changing the relevant end pointer. These are bounded operations independent of n. The worst-case claim concerns arbitrary nodes, including the tail.

Original paper, page 10 · Answer key

2 marks · MCQ
Report issue

Heaps & Priority Queues

Question 46, GATE 2023: A priority queue of n elements is implemented as a max-heap. What are the worst-case times for Extract-Max (remove maximum and restore heap) and Insert (add key and restore heap)? A both O(1); B both O(log n); C O(1),O(n); D O(1),O(log n).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

A binary heap has heightΘ(log n). Extract-Max removes the root, moves the final element there, and can sift it down the full height. Insertion appends a leaf and can sift it up the full height. Both therefore take O(log n) worst-case time, option B, under the ordinary heap-storage model without charging an occasional external dynamic-array resize.

Teaching detail. Reading a heap's maximum is O(1) because it is at the root, but Extract-Max includes deletion and restoration, which is more work. A replacement root may be smaller than descendants all the way to a leaf, requiring one comparison/swap step per level. A newly inserted large key may similarly rise from its leaf to the root. A complete binary tree has logarithmic height, giving both upper bounds, and such examples attain that height. Neither operation scans all n items in the ordinary representation.

Original paper, page 49 · Answer key

2 marks · NAT
Report issue

Stacks & Queues

Question 59, GATE 2023: Start with empty stack S and queue Q. Push/enqueue 1,5,7,8,9,2 in that order into each. Then pop S, dequeue Q, pop S, dequeue Q. Four times, dequeue Q and push that element into S. Finally pop S twice. What is the remaining top?
Tap to enlarge
Answer & solution

Official answer: 8

Step through it (24 steps)

Write the stack from bottom to top. After the initial pushes it is [1, 5, 7, 8, 9, 2], and the queue front-to-back is [1, 5, 7, 8, 9, 2]. The two pops remove 2 and 9; the two dequeues remove 1 and 5. The stack is then [1, 5, 7, 8] and the queue [7, 8, 9, 2]. Operation VII and its three repetitions append 7, 8, 9, 2 to the stack. The final two pops remove 2 and 9, leaving top element 8.

Teaching detail. Use different ends for the two structures: a stack removes the most recently pushed item, while a queue removes the earliest enqueued one. After the four transfers, the stack bottom-to-top is [1,5,7,8,7,8,9,2] and the queue is empty. Removing its top two entries leaves [1,5,7,8,7,8], whose final entry is 8. Operation VIII says repeat VII three times after its first execution, making four transfers total. Mistaking this for only three transfers changes the trace.

Original paper, page 62 · Answer key

1 mark · MCQ
Report issue

Arrays & Linked Lists

Question 15, GATE 2022: Reverse the links of an n-node singly linked list using O(1) auxiliary space, e.g. head→a→b→c→NULL becomes head→c→b→a→NULL. What is the best worst-case time? A Θ(n); B Θ(n log n); C Θ(n²); D impossible in O(1) space.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Keep previous, current and next pointers. Save current.next, reverse that link, and advance; at termination previous becomes the head. This uses constant auxiliary space and one pass, O(n). Reversing the links of an arbitrary n-node list requires Ω(n) link changes, so the optimum is Θ(n), A.

Executable pointer pseudocode:
prev=NULL; cur=head;
while(cur!=NULL){ next=cur.next; cur.next=prev; prev=cur; cur=next; }
head=prev;
Loop invariant: prev heads the already reversed prefix and cur heads the untouched suffix; saving next prevents losing the suffix. Only three pointer variables are needed, independent of n.

Original paper, page 13 · Answer key

1 mark · MCQ
Report issue

Hashing

Question 16, GATE 2022: Hash n keys into m slots, using simple-uniform hash function h1 for odd keys and h2 for even keys. Find the expected occupancy of a fixed slot. A m/n; B n/m; C 2n/m; D n/(2m).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

For a fixed slot, each key maps there with probability 1/m under whichever uniform hash function applies to its parity. Summing n indicator expectations gives n/m. Independence between all indicators is unnecessary for this expectation. Thus B.

Let Ii=1 if key i lands in the chosen slot, and 0 otherwise. Occupancy X=ΣIi. Whether i is odd or even, E[Ii]=1/m, so E[X]=ΣE[Ii]=n/m. Using two functions does not double the number of keys or halve the table.

Original paper, page 13 · Answer key

1 mark · NAT
Report issue

Binary Search & Balanced Trees

Question 28, GATE 2022: A BST with 1000 distinct keys is a complete binary tree, stored in zero-based heap-array positions 0…999. At what index is its third-largest key?
Tap to enlarge
Answer & solution

Official answer: 509

The maximum key lies on the right spine, with zero-based array indices 0, 2, 6, 14, 30, 62, 126, 254, 510. Index 510 has no children because their indices exceed 999. The predecessor is its parent 254. The next predecessor is the maximum in 254’s left subtree, rooted at 509; 509 has no children either. Hence the third largest key is at index 509.

The heap-array formulas are left(i)=2i+1, right(i)=2i+2; they locate nodes, not key ordering. BST ordering implies reverse inorder visits largest first. At 254, the right child is 510 and left child 509. Both are leaves, so the first three reverse-inorder positions are 510,254,509.

Original paper, page 22 · Answer key

2 marks · NAT
Report issue

Stacks & Queues

Question 62, GATE 2022: Q1 initially contains four elements in front-to-back order 1,2,3,4 and Q2 is empty. Only Enqueue and Dequeue on either queue are permitted, with no extra storage. End with Q1 empty and Q2 front-to-back 4,3,2,1. What minimum number of Enqueue operations on Q1 is necessary?
Tap to enlarge
Answer & solution

Official answer: 0

No enqueue into Q1 is necessary. Move its front item to Q2, then rotate Q2 by moving each of its previously present items from front to back. Starting with Q2 empty, the successive states after these steps are [1], [2, 1], [3, 2, 1], [4, 3, 2, 1]. Each insertion is Enqueue(Q2, Dequeue(Q1)), and rotations are Enqueue(Q2, Dequeue(Q2)); Q1 is never enqueued. Since the count cannot be negative, the minimum is 0. As in the allowed operation model, a dequeued value can be passed directly to enqueue without an auxiliary storage data structure.

Construction using only queue operations: after transferring item k from Q1 to Q2, rotate Q2 exactly k−1 times by Enqueue(Q2,Dequeue(Q2)). Before rotation Q2=[k−1,…,1,k], and afterward [k,k−1,…,1]. Induction establishes reversal after four transfers. The rotations cost enqueues on Q2, which the objective does not count.

Original paper, page 40 · Answer key

1 mark · MCQ
Report issue

Binary Search & Balanced Trees

Question 10, GATE 2021: A binary search tree T has n distinct elements. What is the time complexity of picking an element smaller than its maximum? A Θ(n log n); B Θ(n); C Θ(log n); D Θ(1). The task implicitly requires n≥2.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

If the root has a right child, the root itself is smaller than the maximum. If it has no right child, it is the maximum, so return its left child. For n≥2 that child exists in the latter case. Only a constant number of pointer tests is needed, Θ(1), D. The task implicitly needs at least two nodes; no such element exists for n=1.

An O(1) algorithm is: if root.right is non-null, return root.key; otherwise return root.left.key. In the first branch some right-subtree key is greater than the root, proving the root is not maximum. In the second branch the root is maximum; distinctness ensures its left child is strictly smaller. Searching for the second-largest element would be a different, potentially height-dependent task; the question asks for any smaller element.

Original paper, page 16 · Answer key

1 mark · NAT
Report issue

Stacks & Queues

Question 21, GATE 2021: An initially empty stack executes push(54); push(52); pop(); push(55); push(62); s=pop(). An initially empty queue executes enqueue(21); enqueue(24); dequeue(); enqueue(28); enqueue(32); q=dequeue(). Find s+q.
Tap to enlarge
Answer & solution

Official answer: 86

Step through it (14 steps)

The first pop removes 52. After pushing 55 and 62, the next pop gives s=62. In the queue the first dequeue removes 21, leaving 24 at the front even after 28 and 32 are enqueued. Thus q=24 and s+q=86.

Write stack contents bottom-to-top: [54], [54,52], [54], [54,55], [54,55,62], then pop returns 62. Write queue contents front-to-back: [21], [21,24], [24], [24,28], [24,28,32], then dequeue returns 24. The stack is last-in-first-out and the queue first-in-first-out. Recording contents after every operation prevents confusing the earlier discarded pop/dequeue results with s and q.

Original paper, page 21 · Answer key

2 marks · MSQ
Report issue

Hashing

Question 47, GATE 2021: Dynamic hashing uses a four-entry table indexed by the lowest two bits of four-bit integer keys. Collisions split into a binary tree by the third-lowest bit (0 left,1 right), then the fourth-lowest bit; split only when required. Target diagram: bucket 00 empty; bucket 01 splits at bit 3, with a leaf on branch 0 and a bit-4 split with two leaves on branch 1; bucket 10 splits at bit 3 into two leaves; bucket 11 has one leaf. Which insertion sequence yields it? A 5,9,4,13,10,7; B 9,5,10,6,7,1; C 10,9,6,7,5,13; D 9,5,13,6,10,14.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: C

The displayed shape requires bucket 00 empty; bucket 01 with one key having third-lowest bit 0 and two keys having third-lowest bit 1, separated by the fourth bit; bucket 10 with one key on each third-bit branch; and bucket 11 with one key. C supplies bucket01={9(1001), 5(0101), 13(1101)}, bucket10={10(1010), 6(0110)}, and bucket11={7(0111)}, exactly that structure. A puts 4 in bucket00, B splits the zero third-bit branch of bucket01 because it contains 1 and 9, and D leaves bucket11 empty while putting three keys in bucket10. Only C matches.

Process C explicitly: 10=1010 enters bucket10; 9=1001 enters bucket01; 6=0110 collides in bucket10 but differs from 10 in bit3, making its two leaves. Key 7=0111 occupies bucket11. Key 5=0101 collides with 9 in bucket01 and goes to its bit3=1 branch, whereas 9 has bit3=0. Finally 13=1101 joins 5 on bit3=1 and differs in bit4, producing exactly the extra split. A premature split without collision would violate the stated rule.

Original paper, page 38 · Answer key

1 mark · MCQ
Report issue

Heaps & Priority Queues

Question 2, GATE 2021: A binary min-heap of n elements is stored as an array. Find optimal worst-case time to find its maximum. A Θ(1); B Θ(log n); C Θ(n); D Θ(n log n).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

A maximum occurs among the heap leaves, of which there are ceil(n/2). Scan those leaves to find it in O(n). Their values have no heap-imposed relative order, so in the worst case each must be considered, yielding Ω(n). Hence Θ(n), C.

In a one-based heap array, indices floor(n/2)+1 through n are leaves. Initialize best to the first leaf and compare each remaining leaf once. Heap order says ancestors are no larger than descendants, so inspecting internal nodes is unnecessary. An adversary can assign distinct arbitrary values to leaves above all internal values; finding their maximum requires leaf-count−1 comparisons.

Original paper, page 55 · Answer key

1 mark · NAT
Report issue

Tree Properties & Traversals

Question 16, GATE 2021: A complete binary tree has 7 nodes. A is the first three BFS-discovered nodes from root; B is the first three DFS-discovered nodes from root. Find |A−B|.
Tap to enlarge
Answer & solution

Official answer: 1

The complete seven-node tree has three levels. BFS first visits the root and both children. DFS discovery first visits the root, one child, and one grandchild. Therefore exactly one BFS member, the other child of the root, is absent from the first three DFS members, so |A−B|=1.

Name the root r, children l,u and grandchildren l1,l2,u1,u2. BFS gives {r,l,u}. A left-first DFS gives {r,l,l1}; right-first gives {r,u,u1}. In either case the intersection has two nodes and the BFS-only set has one. The result is independent of which child is explored first.

Original paper, page 64 · Answer key

1 mark · MCQ
Report issue

Binary Search & Balanced Trees

Question 5, GATE 2020: A BST preorder is 15,10,12,11,20,18,16,19. Find postorder. A 10,11,12,15,16,18,19,20; B 11,12,10,16,19,18,20,15; C 20,19,18,16,15,12,11,10; D 19,16,18,20,11,12,10,15.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step through it (19 steps)

Worked explanation

Preorder lists root, left subtree, right subtree; the BST ordering tells us where the left subtree ends. The reconstructed tree has edges 15→10(left),15→20(right),10→12(right),12→11(left),20→18(left),18→16(left),18→19(right). Postorder recursively visits left, right, root, hence the entire left subtree appears before the right subtree and 15 must be last. Option A is sorted inorder, C follows a different ordering, and D puts the right subtree before the left. This explicit edge list also makes the reconstruction checkable without a picture.

Derivation and answer

Root15 splits the preorder into left10, 12, 11 and right20, 18, 16, 19. On the left, 10 has right child12 with left child11, giving postorder 11, 12, 10. On the right, 20 has left child18 with children 16, 19, giving 16, 19, 18, 20. Append the root: 11, 12, 10, 16, 19, 18, 20, 15, B.

Original paper, page 5 · Answer key

1 mark · MCQ
Report issue

Binary Search & Balanced Trees

Question 6, GATE 2020: What is the worst-case time to insert n² elements into an AVL tree initially containing n elements? A Θ(n⁴); B Θ(n²); C Θ(n² log n); D Θ(n³).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Worked explanation

With m nodes, an AVL tree has height Θ(log m); locating an insertion position and propagating height changes take O(log m), while rotations do not introduce a larger order. During the sequence, m=n+i for 0≤i<n². Thus the total upper bound is Σ O(log(n+i))≤n² O(log(n+n²))=O(n² log n). For ordinary comparison-based insertion of distinct keys, an AVL tree’s external search paths have logarithmic depth; in particular an adversarial sequence can repeatedly force logarithmic work. A constant fraction of n² operations therefore contributes Ω(n² log n). Do not multiply by an extra n for rebalancing.

Derivation and answer

Throughout the n² insertions the AVL size lies between n and n+n², so each logarithmic insertion is O(log n). Their total is O(n²log n), and worst-case searches over a constant fraction of the later insertions require Ω(log n) each. Hence Θ(n²log n), C.

Original paper, page 5 · Answer key

1 mark · MCQ
Report issue

Arrays & Linked Lists

Question 16, GATE 2020: Find worst-case time to insert n elements into an initially empty ordinary linked list while keeping it sorted. A Θ(n); B Θ(n log n); C Θ(n²); D Θ(1).
Question 16, GATE 2020: Find worst-case time to insert n elements into an initially empty ordinary linked list while keeping it sorted. A Θ(n); B Θ(n log n); C Θ(n²); D Θ(1).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Worked explanation

The pointer rewiring for insertion is constant time once the predecessor is known. The expensive part is finding that predecessor. For the ith insertion a singly or doubly linked list can require Θ(i) node visits, since it has no random-access midpoint for binary search. Summing i from 0 to n−1 gives n(n−1)/2, which is Θ(n²). A tail pointer can make some input orders cheap but not all possible insertion positions; the question asks for worst case. Sorting the complete input first changes the online-maintenance task and is not the ordinary operation being analyzed.

Derivation and answer

Maintaining the list in sorted order after each online insertion can require scanning all current nodes to locate the insertion point. Summing worst-case costs 0+1+…+(n−1) givesΘ(n²), C. This assumes the ordinary linked-list representation without an auxiliary search index or presorting all future inputs.

Original paper, page 8 · Answer key

1 mark · NAT
Report issue

Hashing

Question 23, GATE 2020: Double hashing uses h1(k)=k mod 23, h2(k)=1+(k mod 19), and table size 23. Probe numbering starts at 0. What address is returned at probe 1 for key 90?
Tap to enlarge
Answer & solution

Official answer: 13

Worked explanation

Double hashing uses h(k,i)=(h1(k)+i·h2(k)) mod m. Since 90=3×23+21, h1=21. Since 90=4×19+14, h2=1+14=15. The requested i=1 is the second probe, because i=0 gives the initial position. Add the step once and wrap around: (21+15) mod 23=13. Further probes would be 5,20,…, but their occupancy is irrelevant because only the address of a specified probe is requested.

Derivation and answer

h1(90)=90 mod23=21 and h2(90)=1+(90 mod19)=15. Probe1 is(21+1·15)mod23=36mod23=13. Probe0 would have been 21.

Original paper, page 8 · Answer key

2 marks · MCQ
Report issue

Binary Search & Balanced Trees

Question 41, GATE 2020: A balanced BST holds n keys. Reporting all keys in [a,b] produces k outputs. What is the optimal worst-case complexity? A Θ(log n); B Θ(log n+k); C Θ(k log n); D Θ(n log k).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Worked explanation

A pruned inorder routine is: if node is null return; if key>a recurse left; if a≤key≤b output key; if key<b recurse right. With distinct keys, subtrees excluded by the interval are not scanned. Nodes visited without being reported lie along at most the two boundary-search paths, of height O(log n); every other visited node contributes an output. Thus a single traversal costs O(log n+k). Performing a fresh root-to-key successor search for each result would give an avoidable O(k log n). For a lower bound, a query locating a narrow boundary can require logarithmic comparisons and actually emitting k keys needs k operations.

Derivation and answer

Search down the balanced BST to find the lower bound a in O(log n). Then enumerate successive in-range keys with an inorder traversal, pruning subtrees entirely outside the interval. Boundary paths cost O(log n) and reported nodes cost O(k), so the total is O(log n+k). A worst-case boundary search needs logarithmic comparisons and reporting k distinct results needs Ω(k) output work. Thus the optimal worst-case bound is Θ(log n+k), B.

Original paper, page 13 · Answer key

2 marks · NAT
Report issue

Heaps & Priority Queues

Question 47, GATE 2020: An array-represented binary min-heap contains 1023 elements. What is the minimum guaranteed number of comparisons needed to find a maximum?
Tap to enlarge
Answer & solution

Official answer: 511

Worked explanation

In a one-based heap array, node i has children 2i and 2i+1 when present. Therefore internal nodes are 1…floor(1023/2)=511 and leaves are 512…1023, totaling 512. Every internal value is at most a descendant leaf value by repeatedly applying the min-heap property, so a maximum exists among leaves. There is no ordering constraint between distinct leaves. In the worst case each of 511 nonwinning leaf candidates must lose a comparison to eliminate it; one comparison can eliminate at most one candidate. A scan maintaining the largest leaf seen uses exactly 511 comparisons and attains that bound.

Derivation and answer

The1023-node complete binary min-heap has 512 leaves, at array positions 512–1023 under one-based indexing. A maximum can be chosen among the leaves; their relative values are otherwise unconstrained by the heap property. Finding the maximum of 512 candidates requires 511 comparisons in the worst case, achievable by a linear scan. This is the optimal guaranteed comparison count, not a claim about every favorable tied instance.

Original paper, page 14 · Answer key

2 marks · MCQ
Report issue

Heap ordering and conversion complexity

Heaps & Priority Queues

Question 40, GATE 2019: Test max-heap statements: I the smallest element is always at a leaf; II the second largest is always a root child; III a max-heap can be built from a BST in Θ(n); IV a BST can be built from a max-heap in Θ(n). Options A I/II/III, B I/II/IV, C I/III/IV, D II/III/IV.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Our answer: A under distinct-key comparison model

1. Under the intended distinct-key model, a max-heap parent is larger than its children. If the smallest key were internal, one of its children would be smaller still, a contradiction. Hence I holds.
2. The largest key is at the root. If the second largest were below depth one, its nonroot parent would have to be larger, producing a third key above it in rank. Thus it must be one of the root's children and II holds.
3. To establish III, traverse the BST once and copy its n keys into an array, costing Θ(n). Then run bottom-up heap construction, also Θ(n), by sifting down internal nodes. Sorting first is not required.
4. IV is false in the general comparison model. If it were possible, arbitrary distinct keys could be heapified in Θ(n), converted to a BST in Θ(n), and output in sorted order by an inorder traversal in Θ(n). That would contradict the Ω(n log n) comparison-sorting lower bound.
5. Therefore the intended true statements are I, II, III: option A. The qualification about distinct keys is material. With repeated minimum values, a minimum can occur at an internal node as well as a leaf, so the literal word 'always' in I is not valid for unrestricted duplicate-key heaps. Specialized bounded-integer models also cannot be silently substituted for comparison complexity.

Original paper, page 13 · Answer key

2 marks · NAT
Report issue

Expected distance between tree leaves

Tree Properties & Traversals

Question 46, GATE 2019: A binary tree T has 8 leaves and every level is full (a perfect tree). Two leaves a,b are selected uniformly and independently. Find the expected number of edges on their unique connecting path, to two decimal places.
Tap to enlarge
Answer & solution

Official answer: 4.25

1. A perfect binary tree with eight leaves has height 3 because 8=2³. All leaves are at depth 3, with the root at depth zero.
2. By symmetry, fix the first chosen leaf a. Independence means b remains uniformly distributed among all eight leaves, including a itself.
3. If b=a, there is one choice and distance 0. Its sibling is one choice at distance 2, via their parent. The two leaves in the other child subtree of the same depth-one ancestor have distance 4.
4. The remaining four leaves lie across the root, so the path goes up three edges and down three: distance 6. The counts 1+1+2+4=8 exhaust all equally likely outcomes.
5. Therefore E[d]=(1×0+1×2+2×4+4×6)/8=34/8=4.25.
6. The zero-distance case is required by independent sampling. Sampling two distinct leaves would instead condition on b≠a and produce 34/7, a different answer. Also, the question's parenthetical definition fixes a perfect tree; the broader textbook meaning 'every internal node has two children' alone would not determine these distances.

Original paper, page 14 · Answer key

1 mark · MCQ
Report issue

Queue operations on a singly linked list

Arrays & Linked Lists

Question 3, GATE 2018: A noncircular singly linked queue stores head and tail pointers. Enqueue inserts at head; dequeue removes tail. For n nodes, choose the optimal worst-case time pair: A Θ(1),Θ(1); B Θ(1),Θ(n); C Θ(n),Θ(1); D Θ(n),Θ(n).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Method

Enqueue sets new.next=head and head=new, also initializing tail if previously empty. Tail removal must change the predecessor’s next pointer to null and make it the new tail. A tail pointer identifies the node to remove but not its predecessor, because links point only forward. Scanning from head is unavoidable with only these stored pointers. Reversing the operation orientation would allow constant-time deletion at head, but that is not this question’s data structure.

Solution

Inserting at the head updates a constant number of pointers, Θ(1). Removing the tail requires locating its predecessor, which a singly linked list with only head/tail pointers does not directly supply; traversing n nodes costsΘ(n) in the worst case. Thus B.

Original paper, page 4 · Answer key

1 mark · NAT
Report issue

Reconstructing a binary tree height

Tree Properties & Traversals

Question 20, GATE 2018: Postorder is 8,9,6,7,4,5,2,3,1 and inorder is 8,6,9,4,7,2,5,1,3. Height counts edges on a longest root-to-leaf path. Find the height.
Tap to enlarge
Answer & solution

Official answer: 4

Method

Postorder ends with the root, and inorder splits each subtree into left part, root, right part. Root 1 splits off right leaf 3. Its left subtree ends in 2, whose inorder split leaves right leaf 5 and left subtree rooted at 4. Continuing gives 4 with children 6 and 7, and 6 with children 8 and 9. There are five vertices but four edges on the longest path, so do not report the number of levels.

Solution

The final postorder element gives root1, with right child3 and left subtree rooted 2. In that left subtree, 5 is the right child, while 4 is the left child of 2; 4 has left child6 and right child7, and 6 has children 8, 9. A longest path is 1→2→4→6→8, four edges. Thus height 4.

Original paper, page 9 · Answer key

2 marks · NAT
Report issue

Counting seven-key min-heaps

Heaps & Priority Queues

Question 46, GATE 2018: How many distinct min-heaps use each key 1,2,3,4,5,6,7 once? Use the standard complete binary heap shape.
Tap to enlarge
Answer & solution

Official answer: 80

Method

The shape is fixed: a root with two three-node subtrees. Minimum key 1 must occupy the root. Select a three-element subset of the remaining six keys for the left subtree; the right gets the complement, giving C(6,3)=20 distinct assignments. Within each subtree its least key must be its root, but its two leaves can be swapped independently. Left and right positions are distinguished in a heap, so do not divide the count by 2 for mirror images.

Solution

The minimum 1 must be the root. The complete seven-node shape has three positions in each subtree. Choose which three of the other six keys go left in C(6, 3)=20 ways. In either three-node subtree its smallest key is the root and its two leaves can be ordered in 2 ways. Thus there are 20*2*2=80 heaps.

Original paper, page 19 · Answer key

1 mark · MCQ
Report issue

Binary Search & Balanced Trees

Question 6, GATE 2017: A binary search tree has 15 nodes. A one-node tree has height 0. Find minimum and maximum heights. A (4,15); B (3,14); C (4,14); D (3,15).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

1. Height counts edges, so levels 0 through h hold at most 1+2+...+2h=2h+1−1 nodes.

2. For 15 nodes, 2h+1−1≥15 requires h≥3. A perfect four-level tree realizes height 3 and can be assigned sorted BST keys.

3. At the other extreme, a one-child chain uses one edge per additional node, giving 14 edges. No simple root-to-leaf path can exceed 14 edges with 15 nodes. Answer B.

Original paper, page 4 · Answer key

1 mark · MCQ
Report issue

Stacks & Queues

Question 13, GATE 2017: A circular queue uses singly linked nodes, each with one next pointer, and exactly two external pointers FRONT and REAR. For O(1) insertion and deletion, which general structural conditions hold? I:front.next points to rear. II:rear.next points to front. A:I only. B:II only. C:both. D:neither.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

1. For queue order to follow next links, the circular chain must run FRONT → second → ... → REAR → FRONT. Its closing link is therefore REAR.next=FRONT, statement II.

2. To enqueue node u, set u.next=FRONT, REAR.next=u and REAR=u. To dequeue, save the old front, advance FRONT=FRONT.next and set REAR.next=FRONT. Both require only a fixed number of pointer changes, with empty and singleton cases handled separately.

3. If links instead run backward through queue order, removing the front would require finding its predecessor by traversal. Statement I is not the general rule, even though both statements happen to hold in a two-node circle. Choose B.

Original paper, page 5 · Answer key

2 marks · MCQ
Report issue

Binary Search & Balanced Trees

Question 36, GATE 2017: A binary search tree has preorder 12,8,6,2,7,9,10,16,15,19,17,20. Which is its postorder? A:2,6,7,8,9,10,12,15,16,17,19,20. B:2,7,6,10,9,8,15,17,20,19,16,12. C:7,2,6,8,9,10,20,17,19,15,16,12. D:7,6,2,10,9,8,15,16,17,20,19,12.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step through it (27 steps)

1. Preorder visits root,left,right, so the first value 12 is the root. The contiguous values below 12 form its left preorder 8,6,2,7,9,10; the remaining values form right preorder 16,15,19,17,20.

2. Reconstruct the left side: root 8 has left root 6 with children 2 and 7, and right root 9 with right child 10. Its left-right-root postorder is 2,7,6,10,9,8.

3. On the right, root 16 has left child 15 and right root 19 with children 17 and 20. Its postorder is 15,17,20,19,16. Concatenate left postorder, right postorder and final root 12, obtaining B. Sorting the values would instead produce inorder, not postorder.

Original paper, page 14 · Answer key

2 marks · NAT
Report issue

B-Trees & Multiway Search Trees

Question 49, GATE 2017: In a B+ tree, search keys occupy 8 bytes, blocks are 512 bytes, and block pointers occupy 2 bytes. What is the maximum order of the tree?
Tap to enlarge
Answer & solution

Official answer: 52.0

Our answer: 52

1. Use the conventional definition of order m as the maximum number of child pointers in an internal node. Such a node needs m pointers and m-1 separator keys, since keys separate adjacent child ranges.

2. The capacity inequality is 2m+8(m-1)≤512. Expanding gives 10m-8≤512, hence 10m≤520 and m≤52.

3. At m=52, the node uses 104 pointer bytes plus 408 key bytes, exactly 512. Increasing to 53 would require 522 bytes, so the maximum is 52. This is an internal-node calculation that ignores unspecified metadata; a different convention defining order as the number of keys must not be substituted silently.

Original paper, page 20 · Answer key

1 mark · MCQ
Report issue

Stacks & Queues

Question 10, GATE 2016: An efficiently implemented array-based queue contains n items. Which complexity statement is correct? A: Both ENQUEUE and DEQUEUE can be O(1). B: At most one is O(1), with the other worst-case Ω(n). C: Both are worst-case Ω(n). D: Both are worst-case Ω(log n).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

A fixed-capacity circular array stores front/rear indices and wraps them modulo capacity. Enqueue writes at rear and advances it; dequeue reads at front and advances it. Both take O(1) without shifting elements, A, with overflow handled separately from dynamic resizing.

Maintain an item count or an extra full/empty flag to distinguish a full circular queue from an empty one when indices coincide. Each operation performs a bounded number of array accesses and index updates independent of n. Removing the head does not require compacting the stored elements because the front index identifies the new head. An implementation that shifts every item is possible, but the question asks what an efficient representation can achieve, not what every array implementation does.

Original paper, page 5 · Answer key

2 marks · MCQ
Report issue

Heaps & Priority Queues

Question 37, GATE 2016: An array-stored binary heap has depth d, measured in root-to-farthest-leaf edges. After deleting the item at arbitrary index i, what is the efficient worst-case time for restoring heap order? A: O(1). B: O(d) but not O(1). C: O(2^d) but not O(d). D: O(d·2^d) but not O(2^d).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Replace the deleted element with the last heap element, reduce the heap size, then sift up if the parent order is violated or otherwise sift down. At most one root-to-leaf path is traversed, length≤d. Some deletions require movement throughΘ(d) levels, so the worst-case bound is O(d) and not O(1), B.

Replacing the deleted slot with the last array element preserves the complete-tree shape and avoids shifting an entire subtree. For a min-heap, compare the replacement with its parent: if it is too small, move it upward; otherwise any violation can only be below it, so move it downward by choosing the smaller child. The max-heap case reverses inequalities. There are at most d edges on the chosen path, with constant work at each, and worst-case inputs require traversal to the root or deepest leaf.

Original paper, page 15 · Answer key

2 marks · NAT
Report issue

Stacks & Queues

Question 41, GATE 2016: Initially queue Q holds 16 numbers and stack S is empty. Head and Top inspect without removing. Repeat while Q is nonempty: if S is empty or Top(S)≤Head(Q), dequeue Q's head and push it on S; otherwise pop S's top and enqueue it at Q's tail. What is the maximum number of loop iterations?
Tap to enlarge
Answer & solution

Official answer: 256.0 : 256.0

Our answer: 256

Let F(n) be the maximum number of loop iterations with n queued values and no relevant stack entries. Until a minimum queued value is pushed, each value originally preceding that minimum is pushed at most once and popped at most once: popped items return behind the minimum. Thus this phase costs at most 2n−1 iterations. Once the minimum is pushed it never pops, leaving at most n−1 values to process above it. Hence F(n)≤2n−1+F(n−1), giving F(n)≤n². A strictly descending initial queue attains equality at each phase, because all preceding values are pushed and popped and return in descending order behind the minimum. Therefore F(16)=256.

Each loop iteration moves one item either from Q to S or from S to Q. For a descending input 16,15,...,1, the first phase moves 15 earlier values onto the stack and back off before finally pushing 1:31 moves. That 1 never leaves, and the remaining values are again descending, giving phases 29,27,...,1. Their sum is 162=256. The upper-bound argument counts at most one push and one pop before the next minimum is fixed, so the example achieves the maximum rather than merely a large runtime.

Original paper, page 16 · Answer key

1 mark · NAT
Report issue

Tree Properties & Traversals

Question 11, GATE 2016: BFS starts at the root of a binary tree. Vertex t is at distance 4 from the root and is the nth visited vertex, counting the root first. Find the maximum n.
Tap to enlarge
Answer & solution

Official answer: 31.0 : 31.0

Our answer: 31

BFS visits all shallower levels first. A full binary tree has 1+2+4+8=15 nodes above level4 and at most 16 nodes on level4. Taking t last on that level gives position 31, attained by a perfect tree through level4.

The last possible position at depth d in a binary tree is Σ(k=0 to d)2k=2d+1−1. Nodes at greater depth cannot precede t in BFS. Sparse levels or placing t earlier can only reduce its ordinal, so a full tree and a last-on-level choice attain the bound.

Original paper, page 28 · Answer key

1 mark · MCQ
Report issue

Arrays & Linked Lists

Question 15, GATE 2016: A sorted doubly linked list initially holds N items. Delete and decrease-key receive pointers to their records. An algorithm performs, in order, Θ(N) deletes, O(log N) inserts, O(log N) finds and Θ(N) decrease-key operations. Select total time: A O(log²N); B O(N); C O(N²); D Θ(N² log N).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

With the node pointer, doubly linked deletion is O(1). Maintaining sorted order can require O(N) search per insertion, find, or decrease-key repositioning. Thus Θ(N) deletions cost O(N), O(log N) insert/find calls cost O(N log N), and Θ(N) decreases cost O(N²) in the worst case. Total O(N²), C; the deletion count may leave Θ(N) elements, allowing this worst case.

A pointer removes the need to locate a node for deletion, but decreasing its key may move it far left to preserve order. Relinking is constant time; locating the new position can be linear. A linked list does not permit constant-time access to a middle index, so sortedness alone does not give array-style logarithmic binary search.

Original paper, page 29 · Answer key

2 marks · NAT
Report issue

Heaps & Priority Queues

Question 34, GATE 2016: A complete binary min-heap contains each integer 1,…,1023 exactly once. Root depth is 0. What is the greatest possible depth of key 9?
Tap to enlarge
Answer & solution

Official answer: 8.0 : 8.0

Our answer: 8

A node at depth d has d strictly smaller ancestors in a heap of distinct keys. Key9 has only eight smaller values, so d≤8, also below the full tree’s maximum depth 9. Place1..9 along a root-to-depth 8 chain and assign remaining keys in a parent-before-child order; all heap inequalities can be satisfied. Thus depth 8 is attainable.

There are 1023=210−1 nodes, so levels 0 through 9 exist. Depth 9 would require nine ancestors smaller than 9, but only eight values qualify. A heap is not a BST: siblings need not be numerically ordered, so the remaining values can be assigned without imposing a search-tree constraint on the chosen chain.

Original paper, page 34 · Answer key

2 marks · MCQ
Report issue

Tree Properties & Traversals

Question 36, GATE 2016: New-order visits root, then right subtree, then left subtree recursively. For the expression tree of postfix “3 4 * 5 - 2 ^ 6 7 * 1 + -”, choose its New-order. A + - 1 6 7 * 2 ^ 5 - 3 4 *; B - + 1 * 6 7 ^ 2 - 5 * 3 4; C - + 1 * 7 6 ^ 2 - 5 * 4 3; D 1 7 6 * + 2 5 4 3 * - ^ -.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step through it (15 steps)

The postfix expression gives root subtraction with left subtree((3*4)−5)2 and right subtree(6*7)+1. Root-right-left order visits −, then + 1 * 7 6, then ^ 2 − 5 * 4 3. Thus − + 1 * 7 6 ^ 2 − 5 * 4 3, C.

Build the tree with a stack: push operands; for an operator pop the right child first, then the left child. The final minus combines the two large subexpressions. Reversing child visits does not exchange the operands in the original expression; it changes only traversal order. In particular the right multiplication is visited * 7 6, excluding B.

Original paper, page 35 · Answer key

2 marks · NAT
Report issue

Binary Search & Balanced Trees

Question 40, GATE 2016: How many permutations of 1,…,7, inserted into an empty BST, produce height 6? Height counts edges, so a one-node tree has height 0.
Tap to enlarge
Answer & solution

Official answer: 64.0 : 64.0

Our answer: 64

Height6 with seven nodes means every node lies on one chain. The first inserted value must be the smallest or largest remaining key; otherwise both subtrees would be nonempty and the tree could not be a chain. Recursively choose either endpoint for each of the first six insertions, with the last forced. This gives 26=64 distinct insertion orders.

For a chain, all remaining keys must fall on one side of each successive root. Thus the smallest or largest key is chosen repeatedly. This counts insertion permutations, not merely final shapes. For three keys the valid orders are 123,132,312,321, illustrating the recurrence C(k)=2C(k−1), C(1)=1.

Original paper, page 36 · Answer key

1 mark · MCQ
Report issue

Tree Properties & Traversals

Question 15, GATE 2015: Height means the length in edges of the longest root-to-leaf path. Find maximum and minimum node counts of a binary tree of height 5. A 63 and 6; B 64 and 5; C 32 and 6; D 31 and 5.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Levels run from depth 0 through 5. At most 2d nodes fit at depth d, so the maximum is the geometric sum 26−1=63. The minimum still requires one path containing five edges, hence six vertices. The number 32 counts only the possible last-level nodes, not the entire tree.

Solution: Height5 counts edges. The complete tree has 1+2+4+8+16+32=63 nodes; a single path needs 6. Thus maximum 63 and minimum 6, A.

Original paper, page 7 · Answer key

1 mark · MCQ
Report issue

Binary Search & Balanced Trees

Question 17, GATE 2015: Which sequences can be inorder traversals of BSTs? I 3,5,7,8,15,19,25; II 5,8,9,12,10,15,25; III 2,7,10,8,14,16,20; IV 4,6,7,9,18,20,25. A I and IV; B II and III; C II and IV; D II only.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

For distinct keys, recursively visiting left subtree, root, then right subtree produces strictly increasing order. I and IV meet this necessary condition and can be realized, for example, by inserting their keys in ascending order into right chains. II descends from 12 to 10, and III from 10 to 8, violating the property.

Solution: Inorder traversal of a BST with distinct keys must be increasing. I and IV are increasing. II places 12 before 10, and III places 10 before 8. Therefore I and IV, A.

Original paper, page 8 · Answer key

1 mark · MCQ
Report issue

Binary Search & Balanced Trees

Question 35, GATE 2015: What are worst-case insertion and deletion costs in a binary search tree with n keys? A Θ(log n),Θ(log n); B Θ(n),Θ(n); C Θ(n),Θ(log n); D Θ(log n),Θ(n).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

BST operations take O(h) time in terms of tree height h. Without a balancing guarantee, sorted insertion can create a chain with height n−1. Insertion may search to its bottom, and deletion of a specified key may likewise require a full-height search, with successor/predecessor work also bounded by height. Logarithmic guarantees require a balanced structure, which is not stated.

Solution: An unbalanced BST can be a chain of n nodes. Finding an insertion position or locating a node for deletion can then traverse Θ(n) nodes, so both worst-case costs are linear, B.

Original paper, page 13 · Answer key

2 marks · MCQ
Report issue

Heaps & Priority Queues

Question 37, GATE 2015: Insert 35 into the max-heap array (indices 1–9) [40,30,20,10,15,16,17,8,4]. A [40,30,20,10,15,16,17,8,4,35]; B [40,35,20,10,30,16,17,8,4,15]; C [40,30,20,10,35,16,17,8,4,15]; D [40,35,20,10,15,16,17,8,4,30].
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step through it (5 steps)

Preserve the complete-tree shape by inserting at the next free index 10, then repair only its ancestor path. Its parent is floor(10/2)=5, holding 15, so swap. At index 5 the parent is 2, holding 30, so swap again. At index 2 the parent is 1, holding 40, so stop. Option C stops too early and violates 30≥35.

Solution: Append35 at index 10. It exceeds its parent15 at index 5, then 30 at index 2, but not 40 at the root. The array becomes 40, 35, 20, 10, 30, 16, 17, 8, 4, 15, option B.

Original paper, page 14 · Answer key

2 marks · MCQ
Report issue

Arrays & Linked Lists

Question 60, GATE 2015: An algorithm performs N inserts and sqrt(log N) each of find, delete, decrease-key on ordered keys. Delete and decrease-key receive pointers to their records. Which structure minimizes total asymptotic cost? A unsorted array; B min-heap; C sorted array; D sorted doubly linked list.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Let k=sqrt(log N). Unsorted insertion is constant amortized time, while each arbitrary-key find scans O(N), giving O(N+Nk)=O(Nsqrt(log N)). Even charging O(N) per deletion for compaction leaves the same order; decrease-key requires no ordering repair. A binary heap's online inserts can cost Θ(Nlog N) altogether and it does not speed arbitrary-key search. Sorted structures pay to locate or maintain insertion positions, potentially Θ(N²). Pointer access removes the search for a deletion target, not the need to preserve a chosen ordering.

Solution: Let k=sqrt(log N). With an unsorted array, N insertions take O(N) amortized and k arbitrary-key finds take O(Nk); pointer-directed deletion and decrease-key need at most O(Nk) total even if compaction work is charged. Total O(Nsqrt(log N)). A standard online binary min-heap costs O(Nlog N) for N worst-case insertions, and arbitrary-key finds are still linear. Maintaining sorted arrays or lists can cost Θ(N²) over the N insertions. Thus the unsorted array is best among the listed textbook online structures, A. This comparison is for the specified operation model, not an alternative offline bulk-sorting/heap-building algorithm.

Original paper, page 22 · Answer key

1 mark · MCQ
Report issue

Heaps & Priority Queues

Question 22, GATE 2015: A complete binary tree has both root subtrees already max-heaps. What lower bound describes operations to turn it into a heap? AΩ(logn), BΩ(n), CΩ(nlogn), DΩ(n²). The intended interpretation is worst-case repair work, not a lower bound for every instance.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Our answer: A for worst-case heap repair

Sift the root down, swapping with the larger child until order is restored. The path can have Θ(log n) levels, and a smallest root with heap-ordered descendants realizes that worst case. Thus the intended worst-case lower bound is Ω(log n), A. It is not a per-instance lower bound: a root already exceeding its children needs only constant checking.

Only the root can violate heap order because its subtrees already satisfy it. Compare the root with its larger child and swap downward as needed; each swap moves the offending value one level. A complete n-node tree has height Θ(logn), and placing a sufficiently small value at the root can force a descent to a leaf. That is the intended worst-case lower bound matched by sift-down. If the root already dominates its children, constant work is enough, so the statement cannot mean every instance requires logarithmic work.

Original paper, page 33 · Answer key

1 mark · NAT
Report issue

Tree Properties & Traversals

Question 23, GATE 2015: A binary tree has 20 leaves. How many nodes have exactly 2 children?
Tap to enlarge
Answer & solution

Official answer: 19

Let n0, n1, n2 count nodes with 0, 1, 2 children. Counting edges gives n1+2n2=n0+n1+n2−1, so n2=n0−1=19, regardless of one-child nodes.

Let L, U, B count leaves, one-child nodes, and two-child nodes. The total nodes are L+U+B, and a tree has one fewer edges. Counting edges by parents instead gives U+2B. Equating U+2B=L+U+B−1 cancels U and gives B=L−1. Hence 20 leaves imply 19 two-child nodes, regardless of how many unary nodes occur.

Original paper, page 34 · Answer key

2 marks · NAT
Report issue

Other / Mixed Topics

Question 48, GATE 2015: Young tableau rows[1, 2, 5, 14], [3, 4, 6, 23], [10, 12, 18, 25], [31, ∞, ∞, ∞], increasing rows/columns. Remove 1 and move other entries so that the result remains a Young tableau, allowing unfilled entries to be marked ∞. What is the minimum number of other entries shifted? The solution below uses the conventional adjacent-hole deletion algorithm.
Tap to enlarge
Answer & solution

Official answer: 5

Standard Young-tableau deletion moves the smaller right/down neighbor into the hole. Removing 1 successively shifts 2, 4, 6, 18, 25, then places infinity at(3, 4), giving five moved entries. At each step selecting a larger adjacent neighbor would violate the row/column inequality with the smaller one, so this is the forced minimum adjacent-shift deletion path.

In conventional adjacent-hole deletion, after removing 1 the hole at the top-left must receive the smaller of its right/down neighbors to preserve both monotonic directions. The forced choices are 2, then 4, then 6, then 18, then 25; the hole finally reaches a position that may become∞. Moving the larger neighbor at an earlier step would leave a smaller value below or to the right of the moved entry, violating order. This proves minimality for the conventional adjacent-hole sliding model, not by itself for arbitrary whole-table rearrangement; the source does not explicitly restrict movements to adjacent cells.

Original paper, page 42 · Answer key

2 marks · MCQ
Report issue

Hashing

Question 50, GATE 2015: Which hash best distributes integers i=0…2020 over buckets 0…9? A i²mod 10; B i³mod 10; C11i²mod 10; D12 imod 10.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Cubing permutes decimal residues: 0, 1, 8, 7, 4, 5, 6, 3, 2, 9. Therefore each block of 10 consecutive keys places one in each bucket. Among 2021 keys bucket 0 gets 203 and every other bucket 202, optimally balanced. Squares use only six residues, 11i² is identical modulo 10, and 12i only reaches even buckets. Thus B.

Only the last decimal digit matters modulo 10. Cubes of residues 0 through 9 give 0, 1, 8, 7, 4, 5, 6, 3, 2, 9, which is a permutation. Each full ten-key block therefore hits every bucket once. The 2021 keys consist of 202 full blocks plus one extra key 0 mod 10, giving counts 203, 202, …, 202, as balanced as possible. Squaring collapses residues, 11i²has the same residues as i², and 12i≡2i can only reach even buckets.

Original paper, page 44 · Answer key

1 mark · NAT
Report issue

Tree Properties & Traversals

Question 21, GATE 2015: A binary tree T has 200 leaf nodes. How many nodes in T have exactly two children? Nodes with exactly one child are allowed.
Tap to enlarge
Answer & solution

Official answer: 199

1. Let n0,n1,n2 count nodes with zero, one and two children. Every non-root node contributes one incoming edge, so E=n0+n1+n2−1. Counting edges from parents instead gives E=n1+2n2; subtracting cancels n1 and yields the result without assuming a full binary tree.

2. Counting tree edges gives n1+2n2=n0+n1+n2−1. Hence the number with two children is n2=n0−1=200−1=199.

Original paper, page 60 · Answer key

1 mark · NAT
Report issue

Hashing

Question 22, GATE 2015: A hash table T has 25 slots and stores 2000 elements. Find its load factor α.
Tap to enlarge
Answer & solution

Official answer: 80

1. Load factor measures the average number of elements per table slot, rather than the fraction of slots that are nonempty. With separate chaining, several elements may share a slot, so a load factor greater than one is meaningful.

2. Load factor is number of stored elements divided by number of slots: 2000/25=80. This is possible with chaining rather than a one-element-per-slot open-addressed table.

Original paper, page 60 · Answer key

1 mark · MCQ
Report issue

Binary Search & Balanced Trees

Question 27, GATE 2015: Insert 71,65,84,69,67,83, in that order, into an initially empty binary search tree. Which element is at the lowest (deepest) level? (A) 65; (B) 67; (C) 69; (D) 83.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step through it (8 steps)

1. Insertion gives root71, left65, right84; 69 is 65’s right child, 67 is 69’s left child, 83 is 84’s left child.

2. The deepest node is 67 at depth 3, B.

Original paper, page 62 · Answer key

1 mark · MCQ
Report issue

Stacks & Queues

Question 28, GATE 2015: Evaluate the postfix expression whose tokens are: 10 5 + 60 6 / * 8 −. Options: (A) 284; (B) 213; (C) 142; (D) 71.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step through it (10 steps)

1. A stack evaluator pops the right operand first and left operand second. After + the stack contains 15; after / it contains 15,10; after * it contains 150; the final subtraction is 150−8, not 8−150.

2. Postfix evaluation gives 10+5=15, 60/6=10, then 15·10=150, and 150−8=142. Thus C.

Original paper, page 62 · Answer key

1 mark · MCQ
Report issue

Heaps & Priority Queues

Question 30, GATE 2015: An array in level-order heap representation is (89,19,50,17,12,15,2,5,7,11,6,9,100). What is the minimum number of interchanges needed to convert it into a max-heap? An interchange swaps two elements. Options: (A) 4; (B) 5; (C) 2; (D) 3.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

1. With 1-based indices, swaps (13,6), (6,3), (3,1) yield (100,19,89,17,12,50,2,5,7,11,6,9,15). Check each parent against its children: every parent is at least as large. This gives a concrete three-swap witness, not merely the count performed by an unspecified heapify routine.

2. Three swaps along the ancestor chain move 100 through indices 13→6→3→1, producing a valid max-heap. Fewer cannot suffice: 100 must reach the root. If swapped directly with 89, the resulting 89 at 13 exceeds both ancestors 15 at 6 and 50 at 3; one additional swap cannot repair both (swapping with 3 leaves 50 below 15; swapping with 6 leaves 89 below 50). If100 reaches the root in two swaps, at least one of the remaining displaced chain values is still out of heap order. Thus the minimum is 3, D.

Original paper, page 63 · Answer key

1 mark · NAT
Report issue

Tree Properties & Traversals

Question 12, GATE 2014: A rooted binary tree with n nodes is represented by pointers. The best upper bound for counting rooted subtrees containing exactly four nodes is O(nᵃ logᵇ n). Find a+10b.
Tap to enlarge
Answer & solution

Official answer: 1

1. Method and setup. Use one postorder traversal. When processing a node, both child-subtree sizes are already known; combine them with the current node and count it if the total is four. Store size and count in the recursion result rather than recounting descendants for every possible root.

2. Work through the result and its assumptions. A postorder traversal computes each rooted subtree size as 1+left_size+right_size and increments a counter for size 4. It does constant work per node, Θ(n)=O(n¹log⁰n), so a+10b=1.

Original paper, page 10 · Answer key

2 marks · MCQ
Report issue

Hashing

Question 40, GATE 2014: A nine-slot hash table uses h(k)=k mod 9 and chaining. Insert keys 5,28,19,15,20,33,12,17,10 in that order. What are the maximum, minimum and average chain lengths over all slots? A: 3,0,1. B: 3,3,3. C: 4,0,1. D: 3,0,2.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (11 steps)

1. Method and setup. Compute each key’s remainder, then count keys in each slot. Chaining does not probe or relocate a colliding key to another slot. Include empty slots when finding the minimum and when averaging: average chain length over the table is total keys divided by total slots.

2. Work through the result and its assumptions. The residues modulo 9 are 5, 1, 1, 6, 2, 6, 3, 8, 1. Slot1 has 3 keys; slots 0, 4, 7 are empty; all 9 slots together hold 9 keys, so average length 1. Maximum3, minimum 0, average 1: A.

Original paper, page 17 · Answer key

1 mark · MCQ
Report issue

Heaps & Priority Queues

Question 12, GATE 2014: A max-heap initially has level order 10,8,5,3,2. Insert 1 and then 7. What is the new level order? A 10,8,7,3,2,1,5; B 10,8,7,2,3,1,5; C 10,8,7,1,2,3,5; D 10,8,7,5,3,2,1.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (5 steps)

1. Set up the reasoning. Represent the heap as a one-based array. Append each item at the first available position to preserve the complete-tree shape, then compare it only with its ancestors while restoring max-heap order.

2. Derive the result. Appending1 puts it below 5 and requires no swap. Appending7 puts it below 5, so exchange 7 and 5; 7 is below root10 and stops. The resulting level order is 10, 8, 7, 3, 2, 1, 5, A.

3. Check the interpretation. Heap insertion does not sort an entire level. Inserting 7 affects the path through its parent 5; it does not exchange the existing siblings 3 and 2. This distinguishes A from other arrays that might still satisfy some heap inequalities.

Original paper, page 32 · Answer key

2 marks · NAT
Report issue

Tree Properties & Traversals

Question 39, GATE 2014: An expression tree has root +. Its left child is -, with children +(a,b) and -(c,d); its right child is +, with children -(e,f) and +(g,h). Every leaf a,b,c,d,e,f,g,h independently takes value 0 or 1. Find the maximum value of ((a+b)-(c-d))+((e-f)+(g+h)).
Tap to enlarge
Answer & solution

Official answer: 6

1. Set up the reasoning. Expand parentheses carefully, especially the subtraction of (c-d). This turns the tree into a linear expression with independent binary variables.

2. Derive the result. Label leaves left-to-right a,..., h. The expression expands as(a+b)−(c−d)+(e−f)+(g+h)=a+b−c+d+e−f+g+h. Set the six positive-coefficient leaves to 1 and the two negative-coefficient leaves to 0. The maximum is 6.

3. Check the interpretation. The d term is positive because it is subtracted twice. Set positive-coefficient leaves to one and negative-coefficient leaves to zero. The resulting assignment attains the coefficient upper bound, so it proves a maximum rather than only an example value.

Original paper, page 40 · Answer key

2 marks · MCQ
Report issue

Stacks & Queues

Question 41, GATE 2014: A stack supports PUSH, POP, and REVERSE, which reverses its current element order. Which statement about implementing a queue is true? A impossible; B ENQUEUE takes one instruction and DEQUEUE two; C ENQUEUE takes three and DEQUEUE one; D both take one.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. Set up the reasoning. Choose and maintain an invariant: the queue's front is always at the stack top. Then removing the front is simply POP; a newly enqueued item must be placed at the bottom without disturbing the old order.

2. Derive the result. Keep the queue front at the stack top. ENQUEUE(x) performs REVERSE, PUSH(x), REVERSE, placing x at the bottom while preserving the previous order. DEQUEUE performs POP. Thus three and one instructions respectively, C. A single reversal followed by a pop would leave the remaining stack in the wrong orientation for an arbitrary future operation sequence.

3. Check the interpretation. REVERSE, PUSH, REVERSE inserts at the bottom and restores the invariant. Counting only the reversal and pop needed for one isolated removal ignores the orientation needed by later queue operations.

Original paper, page 40 · Answer key

1 mark · MCQ
Report issue

Tree Properties & Traversals

Question 12, GATE 2014: An ordered rooted tree has root P with children Q,R from left to right. Q has sole child S. R has children T,U,V from left to right. U has sole child W. Find the stated inorder visit sequence. A SQPTRWUV; B SQPTUWRV; C SQPTWUVR; D SQPTRUWV.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Our answer: A under the ordered-general-tree inorder convention

Step 1: Notice that R has three children, so ordinary binary-tree inorder is not sufficient to define the task. The keyed interpretation uses the ordered-tree extension: traverse the first child, visit the node, then traverse remaining children left to right. Step 2: Under that convention Q's subtree gives S,Q; P is next. R's subtree gives T,R, then U's subtree W,U, then V. Step 3: Concatenate to obtain S,Q,P,T,R,W,U,V, option A. The source's missing convention remains a qualification rather than silently treating the drawing as binary.

Original paper, page 55 · Answer key

2 marks · NAT
Report issue

Binary Search & Balanced Trees

Question 39, GATE 2014: An unaugmented balanced BST T stores n numbers. There are m keys in the interval from L to H, whose sum must be computed. If the tightest upper bound is O(nᵃ logᵇ n + mᶜ logᵈ n), find a+10b+100c+1000d.
Tap to enlarge
Answer & solution

Official answer: 110

Step 1: Use the search ordering to locate the interval's first relevant key or its boundary in O(log n), since the tree is balanced. Step 2: Traverse the m matching keys in inorder while pruning subtrees wholly outside the interval. With a traversal stack, the total is O(log n+m), not m independent root-to-key searches costing O(m log n). Step 3: Match this to the displayed form: n⁰log¹n + m¹log⁰n, so (a,b,c,d)=(0,1,1,0). The requested encoding is 0+10+100+0=110. Subtree-sum augmentation was not specified and would change the range-sum method.

Original paper, page 61 · Answer key

2 marks · MCQ
Report issue

Hashing

Question 40, GATE 2014: A 100-slot hash table resolves collisions by chaining and uses simple uniform hashing. What is the probability that slots 1,2,3 are all empty after three insertions? A 97³/100³; B (99×98×97)/100³; C (97×96×95)/100³; D (97×96×95)/(3!×100³).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step 1: For a given insertion, 97 of the 100 equally likely slots avoid the three prohibited slots, so its avoidance probability is 97/100. Step 2: Under simple uniform hashing the three placements are independent. Chaining permits multiple inserted keys to use the same allowed slot, so the allowed count does not decrease after an insertion. Step 3: Multiply the three factors: (97/100)³, option A. Using 97,96,95 would incorrectly require distinct occupied slots.

Original paper, page 62 · Answer key

2 marks · MCQ
Report issue

Tree Properties & Traversals

Question 41, GATE 2014: An arbitrary tree uses leftMostChild/rightSibling pointers. Function D(t): set value=0; if t is non-NULL, set value=1 when t.leftMostChild is NULL, otherwise set value=D(t.leftMostChild); then add D(t.rightSibling); return value. Passing the root returns what? A internal-node count; B tree height; C number of nodes without right siblings; D leaf count.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Step 1: A NULL pointer returns zero. A node with no child contributes one for itself, identifying a leaf. A node with children contributes only the recursive count from its child list, not one for itself. Step 2: The rightSibling recursion adds the counts of the remaining sibling subtrees. It does not test whether a sibling exists as a property to count. Step 3: Inductively each forest call counts exactly its leaves; at the root, whose sibling pointer is NULL, this is the entire tree's leaf count, D. The recurrence adds branches rather than taking a maximum, so it does not compute height.

Original paper, page 62 · Answer key

1 mark · MCQ
Report issue

Worst-case unbalanced BST insertion

Binary Search & Balanced Trees

Question 7, GATE 2013: Give the tightest listed worst-case upper bound for inserting into an ordinary n-node binary search tree: A O(1), B O(log n), C O(n), D O(n log n).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

In an ordinary unbalanced binary search tree, increasing insertions can create a chain of n nodes. Finding the next insertion position then takes a linear search down that chain. Worst-case insertion is O(n), C, not the logarithmic bound of balanced trees.

Insertion follows the search path until it reaches a missing child, then attaches the new node. Its cost is proportional to tree height. A balanced tree has logarithmic height, but no balance requirement is given. Inserting increasing keys creates a right-child chain; a later larger key must inspect all n existing nodes. Thus linear time is possible and O(n) is the tightest listed worst-case bound.

Original paper, page 2 · Answer key

2 marks · MCQ
Report issue

Recover BST postorder from preorder

Binary Search & Balanced Trees

Question 43, GATE 2013: A BST has preorder 30, 20, 10, 15, 25, 23, 39, 35, 42. Choose postorder: A10, 20, 15, 23, 25, 35, 42, 39, 30; B15, 10, 25, 23, 20, 42, 35, 39, 30; C15, 20, 10, 23, 25, 42, 35, 39, 30; D15, 10, 23, 25, 20, 35, 42, 39, 30.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Step through it (21 steps)

The root is 30. Its preorder left-subtree segment is 20, 10, 15, 25, 23 and its right-subtree segment is 39, 35, 42. Under 20, node 10 has right child 15, and node 25 has left child 23; their postorders are 15, 10 and 23, 25, giving the full left-subtree postorder 15, 10, 23, 25, 20. Under 39 are children 35 and 42, so its postorder is 35, 42, 39. Appending the root gives 15, 10, 23, 25, 20, 35, 42, 39, 30, option D.

Preorder identifies each subtree’s root first. Split the remaining values around 30: values below 30 form the left subtree and above 30 the right. Repeat around 20 and 39. Postorder reverses the placement of each root in the traversal: recursively emit its left subtree, then right subtree, then the root. This yields left block 15, 10, 23, 25, 20 and right block 35, 42, 39, followed by 30. Checking only that 30 is last is insufficient; every nested subtree must satisfy the same rule.

Original paper, page 10 · Answer key

1 mark · MCQ
Report issue

Balanced search tree with exponential size

Binary Search & Balanced Trees

Question 5, GATE 2012: What is the worst-case search time in a balanced binary search tree containing n·2^n elements?
(A) Θ(n log n) (B) Θ(n·2^n) (C) Θ(n) (D) Θ(log n).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

A balanced binary search tree on N elements has worst-case search length Θ(log N). Here N=n·2n, so log₂N=log₂n+n=Θ(n). The answer is C, not Θ(log n), since n itself is not the number of elements.

Check: Search follows just one root-to-leaf branch and performs constant work per visited node. With base-two logarithms, n≤log₂(n2n)≤2n for n≥2, explicitly establishing matching linear upper and lower asymptotic bounds.

Original paper, page 2 · Answer key

2 marks · MCQ
Report issue

Empty and full circular queue conditions

Stacks & Queues

Question 35, GATE 2012: Suppose a circular queue of capacity (n −1) elements is implemented with an array of n elements.
        Assume that the insertion and deletion operations are carried out using REAR and FRONT as array
        index variables, respectively. Initially, REAR = FRONT = 0. The conditions to detect queue full
        and queue empty are
        (A) full: (REAR+1) mod n == FRONT               (B) full: (REAR+1) mod n == FRONT
            empty: REAR == FRONT                            empty: (FRONT+1) mod n == REAR

        (C) full: REAR == FRONT                         (D) full: (FRONT+1) mod n == REAR
            empty: (REAR+1) mod n == FRONT                 empty: REAR == FRONT
Tap to enlarge
Your answer
Answer & solution

Official answer: A

With one of n slots deliberately unused, equal FRONT and REAR denotes the initial empty queue and all subsequent empty states. The queue is full when advancing REAR by one modulo n would collide with FRONT: (REAR+1) mod n=FRONT. These conditions permit n−1 stored elements and distinguish empty from full. Hence A.

Check: For example, with n=4 the usable capacity is three. Starting at FRONT=REAR=0, three insertions advance REAR to 3; its next value would be 0, equal to FRONT, so the full test succeeds without confusing it with the empty state.

Original paper, page 8 · Answer key

2 marks · MCQ
Report issue

Recursive rooted height and wording mismatch

Tree Properties & Traversals

Question 47, GATE 2012: The source defines tree height as “the number of edges on the longest path in the tree” and gives this rooted-tree routine. Fill B1,B2:
int height(treeptr n) {
 if(n==NULL) return -1;
 if(n->left==NULL)
   if(n->right==NULL) return 0; else return B1;
 else { h1=height(n->left);
   if(n->right==NULL) return 1+h1;
   else { h2=height(n->right); return B2; }
 }
}
(A) B1=1+height(n->right), B2=1+max(h1,h2).
(B) B1=height(n->right), B2=1+max(h1,h2).
(C) B1=height(n->right), B2=max(h1,h2).
(D) B1=1+height(n->right), B2=max(h1,h2).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

For the conventional rooted height, a leaf has height 0 and every parent-to-child step adds one edge. If only the right child exists, B1 must be 1+height(n→right). If both exist, B2 must be 1+max(h1, h2). Thus A is the intended rooted-height answer and matches the official key. However, the opening sentence literally defines the longest path anywhere in the tree, which is its diameter, not necessarily its root-to-leaf height. A root with two leaf children has rooted height 1 but diameter 2; none of the listed B2 expressions returns 2 for that example. Preserve this wording defect rather than claiming the code computes the literal definition.

Check: Check a node with only a right leaf: the child returns 0 and the parent must return 1, forcing B1’s +1. With two children, choose the larger subtree height and add the edge from the current node, forcing B2’s +1.

Original paper, page 12 · Answer key

1 mark · MCQ
Report issue

Recognizing a max-heap

Heaps & Priority Queues

Question 23, GATE 2011: Which drawn binary tree is a max-heap? Below each node is specified as value:(left child,right child), with '-' for a missing child.

(A) 10:(8,6), 8:(4,-), 6:(5,2), 5:(1,-); remaining nodes are leaves
(B) 10:(8,6), 8:(4,5), 6:(1,2); remaining nodes are leaves
(C) 10:(5,6), 5:(4,8), 6:(2,1); remaining nodes are leaves
(D) 5:(2,8), 2:(1,4), 8:(6,10); remaining nodes are leaves
Tap to enlarge
Your answer
Answer & solution

Official answer: B

A binary max-heap must have complete-tree shape as well as parent≥child values. B is complete and satisfies 10≥8, 6; 8≥4, 5; 6≥1, 2. A satisfies value order but not completeness. C has child8 greater than parent5; D also violates value order. Thus B.

Completeness requires every level except possibly the last to be full and the last level to be filled from left to right. In A, node 8 lacks a right child while positions to its right are occupied, and a deeper node exists despite that gap. In B every displayed level is full, and every parent dominates its two children. C fails at 5→8; D fails already at 5→8 and also at 2→4 and 8→10. Checking only the root maximum is insufficient.

Original paper, page 6 · Answer key

2 marks · MCQ
Report issue

Unique BST labeling for a fixed shape

Binary Search & Balanced Trees

Question 29, GATE 2011: Given n distinct elements and a fixed unlabeled binary tree with n nodes, in how many ways can the elements populate that tree so it becomes a binary search tree?

(A) 0
(B) 1
(C) n!
(D) binomial(2n,n)/(n+1)
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Inorder traversal of a BST with distinct keys must list them in increasing order. The fixed ordered tree shape has a fixed inorder sequence of node positions, so assign the smallest key to the first position, and so on. This gives exactly one valid labeling, B; Catalan numbers count alternative shapes, not labelings of this supplied shape.

This assumes the usual ordered binary tree, in which left and right child positions are fixed. Inorder visits the entire left subtree, then the node, then the entire right subtree. At each node the BST condition requires every left key to be smaller and every right key larger. Therefore assigning sorted keys along inorder both constructs a valid solution and proves uniqueness. There is at least one solution for any such shape, which rules out zero as well.

Original paper, page 8 · Answer key

1 mark · MCQ
Report issue

Odd subtree sizes in a binary tree

Tree Properties & Traversals

Question 10, GATE 2010: A binary tree has n nodes. Every node has an odd number of descendants, counting the node itself as its own descendant. How many nodes have exactly one child?
Options: (A) 0; (B) 1; (C) (n−1)/2; (D) n−1.
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

The descendants of a node, including itself, form its subtree. If a node had exactly one child, its subtree size would be 1 plus the child’s odd subtree size, hence even. This contradicts the condition at that node. Therefore no node has exactly one child: 0, A.

The parity condition applies to every child subtree as well as the root. A leaf has subtree size 1, which is allowed. A node with two children has size 1+odd+odd, also odd. Exactly one child gives 1+odd, even, which is impossible; thus the hypothesis forces a full binary tree, although it need not be balanced or perfect.

Original paper, page 3

2 marks · MCQ
Report issue

Linear-probing insertion sequence

Hashing

Question 52, GATE 2010: A hash table has length ten, hash function h(k)=k mod 10, open addressing and linear probing. After six insertions into the initially empty table, slots 2,3,4,5,6,7 contain 42,23,34,52,46,33 respectively; slots 0,1,8,9 are empty. Which sequence could have produced this table?
Options: (A) 46,42,34,52,23,33; (B) 34,42,23,52,33,46; (C) 46,34,42,23,52,33; (D) 42,46,33,23,34,52.
Question 52, GATE 2010: A hash table has length ten, hash function h(k)=k mod 10, open addressing and linear probing. After six insertions into the initially empty table, slots 2,3,4,5,6,7 contain 42,23,34,52,46,33 respectively; slots 0,1,8,9 are empty. Which sequence could have produced this table?
Options: (A) 46,42,34,52,23,33; (B) 34,42,23,52,33,46; (C) 46,34,42,23,52,33; (D) 42,46,33,23,34,52.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Simulate option C: 46 hashes to slot 6, 34 to 4, 42 to 2, and 23 to 3. Then 52 starts at 2 and probes occupied slots 2,3,4, stopping at 5. Finally 33 starts at 3 and probes occupied slots 3,4,5,6, stopping at 7. This exactly reproduces the figure. In A, 52 is inserted before 23 and takes slot 3; in B, 33 is inserted before 46 and takes slot 6; in D, 33 takes slot 3 before 23. Those disagree with the shown table, leaving C.

Linear probing tests h(k),h(k)+1,… modulo ten until an empty slot is reached. This means final position depends on insertion order, not only on the hash value. In the valid order, the four home-slot keys 42,23,34,46 establish the required occupied run before the displaced keys arrive. Neither 52 nor 33 wraps around the table in this instance.

Original paper, page 13

2 marks · MCQ
Report issue

Count insertion sequences for a hash table

Hashing

Question 53, GATE 2010: A hash table has length ten, hash function h(k)=k mod 10, open addressing and linear probing. After six insertions into the initially empty table, slots 2,3,4,5,6,7 contain 42,23,34,52,46,33 respectively; slots 0,1,8,9 are empty. How many distinct insertion permutations of these six keys produce this table?
Options: (A) 10; (B) 20; (C) 30; (D) 40.
Question 53, GATE 2010: A hash table has length ten, hash function h(k)=k mod 10, open addressing and linear probing. After six insertions into the initially empty table, slots 2,3,4,5,6,7 contain 42,23,34,52,46,33 respectively; slots 0,1,8,9 are empty. How many distinct insertion permutations of these six keys produce this table?
Options: (A) 10; (B) 20; (C) 30; (D) 40.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

For 52 to reach slot 5, the final occupants 42,23,34 of slots 2,3,4 must already be present. For 33 to reach slot 7, occupants 23,34,52,46 of slots 3,4,5,6 must already be present. Together these constraints make 33 last, and require 42,23,34 before 52; 46 can be anywhere among the first five. Among permutations of the first five keys, 52 must be last among {42,23,34,52}, which happens in 1/4 of the 5! orders. Thus 5!/4=30, option C. These constraints are sufficient because the home-slot keys then occupy their intended slots. Exhaustive simulation of all 720 permutations independently yields 30.

A second count inserts 46 into a sequence containing the other five keys. The first three among those five are 42,23,34 in any of 3! orders, followed by 52 and then 33. The 46 key may be inserted in any of the five gaps before 33, giving 3!×5=30. Inserting it after 33 would allow 33 to occupy slot 6 instead of 7.

Original paper, page 13

2 marks · MCQ
Report issue

Linear-probing hash insertion

Hashing

Question 36, GATE 2009: Insert 12, 18, 13, 2, 3, 23, 5, 15 in an empty 10-slot table using h(k)=k mod 10 and linear probing. Candidate A stores 2:2, 3:23, 5:15, 8:18; B stores 2:12, 3:13, 5:5, 8:18; C stores slots 2–9 as 12, 13, 2, 3, 23, 5, 18, 15; D chains 2:[12, 2], 3:[13, 3, 23], 5:[5, 15], 8:[18]. Other slots empty. Which is correct?
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Step through it (10 steps)

Insertions place 12 at 2, 18 at 8, 13 at 3, 2 at 4, 3 at 5, 23 at 6, 5 at 7 and 15 at 9 after probing past occupied slots 5 through 8. The final slots 2–9 are 12, 13, 2, 3, 23, 5, 18, 15, exactly option C.

Probe consecutive slots until empty. First 12→2 and 18→8; 13→3. Key 2 collides at 2 and 3, so goes 4. Key 3 goes 5; 23 goes 6; 5 goes 7. Finally 15 probes 5, 6, 7, 8 before reaching 9. This yields candidate C. D instead uses chaining, which is explicitly not the requested collision strategy; A/B discard keys rather than preserving them in later empty slots.

Original paper, page 8

2 marks · MCQ
Report issue

Maximum AVL height with seven nodes

Binary Search & Balanced Trees

Question 37, GATE 2009: Maximum edge-height of an AVL tree with 7 nodes, with singleton height 0? A 2; B 3; C 4; D 5.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

The minimum-node recurrence for edge height h is N(h)=1+N(h−1)+N(h−2), with N(−1)=0, N(0)=1. Hence N(1)=2, N(2)=4, N(3)=7, N(4)=12. Seven nodes attain height 3 but cannot reach 4, so B.

To make an AVL tree as tall as possible with few nodes, give its two subtrees heights h−1 and h−2. Thus the minimum nodes at height h obey N(h)=1+N(h−1)+N(h−2). Starting with empty height−1 and singleton 0 gives 0, 1, 2, 4, 7, 12. Seven nodes suffice exactly for height 3, but any height 4 tree needs at least 12. This proves both attainability and impossibility, so B.

Original paper, page 9

2 marks · MCQ
Report issue

Maximum B-plus leaf splits

B-Trees & Multiway Search Trees

Question 44, GATE 2009: Insert 10, 3, 6, 8, 4, 2, 1 into an empty B+ tree. Internal nodes allow at most 3 child pointers; leaves at most 2 data items. What is the maximum number of leaf splits, allowing valid choices of how 3 overflow items split? A 2; B 3; C 4; D 5.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

There can be at most one leaf split per insertion; the first two keys fit in the initial two-item leaf, so at most five splits occur. This bound is attained by leaving two smaller keys in the left leaf and one larger key in the right leaf at each overflow. Starting[3, 10], insertion 6 gives[3, 6]|[10]; 8 gives[3, 6]|[8]|[10]; 4 gives[3, 4]|[6]|[8]|[10]; 2 gives[2, 3]|[4]|[6]|[8]|[10]; 1 gives[1, 2]|[3]|[4]|[6]|[8]|[10]. Thus all five later insertions split a leaf, D. Internal-node splits are not counted. Exhaustive permitted split-choice enumeration confirms the maximum 5.

The first two insertions cannot split a capacity-two leaf. There are only five insertions left and each can overflow at most one leaf, so five is an upper bound. The explicit sequence of valid 1/2 splits in the baseline attains one split on each remaining insertion. That witness proves the maximum, not merely an observed count under one fixed implementation. Promoted separator changes and internal-node splits do not add to the requested leaf-split count.

Original paper, page 10

2 marks · MCQ
Report issue

Recognize an array max-heap

Heaps & Priority Queues

Question 59, GATE 2009: Which zero-based array is a binary max-heap? A[25, 12, 16, 13, 10, 8, 14]; B[25, 14, 13, 16, 10, 8, 12]; C[25, 14, 16, 13, 10, 8, 12]; D[25, 14, 12, 13, 10, 8, 16].
Question 59, GATE 2009: Which zero-based array is a binary max-heap? A[25, 12, 16, 13, 10, 8, 14]; B[25, 14, 13, 16, 10, 8, 12]; C[25, 14, 16, 13, 10, 8, 12]; D[25, 14, 12, 13, 10, 8, 16].
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

In a zero-based heap each parent at i must be at least as large as children at 2i+1 and 2i+2. In C, [25, 14, 16, 13, 10, 8, 12], the checks are 25≥14, 16; 14≥13, 10; and 16≥8, 12, so every edge satisfies max-heap order. A fails because parent 12 has child 13; B fails because parent 14 has child 16; D fails because parent 12 has child 16. Thus C alone is a max-heap.

A max-heap needs parent≥child along every edge, not a globally descending array. In C, root 25 exceeds 14/16; 14 exceeds 13/10; 16 exceeds 8/12. A fails at 12<13; B at 14<16; D at 12<16. Checking only the root would wrongly admit the distractors; every internal node must satisfy the local condition.

Original paper, page 14

2 marks · MCQ
Report issue

Two delete-max operations

Heaps & Priority Queues

Question 60, GATE 2009: Perform two delete-max operations on the valid heap from Q59. Result? A[14, 13, 12, 10, 8]; B[14, 12, 13, 8, 10]; C[14, 13, 8, 12, 10]; D[14, 13, 12, 8, 10].
Question 60, GATE 2009: Perform two delete-max operations on the valid heap from Q59. Result? A[14, 13, 12, 10, 8]; B[14, 12, 13, 8, 10]; C[14, 13, 8, 12, 10]; D[14, 13, 12, 8, 10].
Question 60, GATE 2009: Perform two delete-max operations on the valid heap from Q59. Result? A[14, 13, 12, 10, 8]; B[14, 12, 13, 8, 10]; C[14, 13, 8, 12, 10]; D[14, 13, 12, 8, 10].
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step through it (9 steps)

Start from Q59’s heap [25, 14, 16, 13, 10, 8, 12]. Delete 25, move final element 12 to the root, and sift down by swapping with the larger child 16. The six-element heap is [16, 14, 12, 13, 10, 8]. Delete 16 and move final element 8 to the root: [8, 14, 12, 13, 10]. Swap 8 with larger child 14, then with larger child 13, giving [14, 13, 12, 8, 10]. This is option D. Each deletion removes the maximum and reduces the active heap length by one.

Delete-max replaces the root by the last active element, shrinks the heap and repeatedly swaps downward with the larger child. First deletion moves 12 to the root and swaps it with 16, yielding[16, 14, 12, 13, 10, 8]. Second deletion moves 8 to the root, then swaps with 14 and 13, yielding[14, 13, 12, 8, 10]. Choosing the smaller child would not restore heap order, which explains several plausible-looking alternatives.

Original paper, page 14

2 marks · MCQ
Report issue

Maximum splits in an order-four B-tree

B-Trees & Multiway Search Trees

Question 41, GATE 2008: A B-tree of order 4 is built from empty by ten successive insertions. What is the maximum number of node-splitting operations?

(A) 3
(B) 4
(C) 5
(D) 6
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. An order-four B-tree has at most three keys per node. The maximum is five splits. For ordinary overflow-triggered insertion, inserting 1 through 10 in ascending order and promoting the lower middle key splits a leaf on insertions 4, 6, 8 and 10; the fourth leaf split also overflows and splits the root. For a timing-independent bound, after L leaf splits there are L+1 nonempty leaves. A B-tree with L+1 leaves has exactly L separator keys in all internal nodes combined: each internal node has one fewer key than children, and summing over the tree gives leaves minus one.
2. Consequently n≥(L+1)+L=2L+1. With n=10, L≤4. Under overflow-triggered insertion, the first internal split needs the root to receive four separators from four leaf splits. With no further leaf split possible, no second internal split can occur. Thus there is at most one internal/root split and the total is at most 4+1=5.
3. Under preemptive splitting, the full root may instead split after three leaf splits, distributing its three separators into a new root with one key and two internal children with one key each. At most one further leaf split is possible, which can increase only one such child to two keys; no internal node can become full again. The same upper bound therefore holds, and increasing-key insertion attains five splits under this convention too.

Original paper, page 7

2 marks · MCQ
Report issue

Reconstructing a BST from postorder

Binary Search & Balanced Trees

Question 46, GATE 2008: Given the postorder traversal P of a BST on distinct elements 1,…,n, what is the most efficient time to construct the unique BST having traversal P?

(A) Θ(log n)
(B) Θ(n)
(C) Θ(n log n)
(D) None: the tree cannot be uniquely determined
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Θ(n) time is sufficient and necessary. Read the postorder sequence backward: the next element is the root, followed by the right subtree in reverse postorder and then the left.
2. A recursive builder with allowed key interval (low,high) consumes a value only if it belongs in that interval; after creating a node with key r, build the right interval (r,high), then the left (low,r). Each key is consumed once and there are O(n) calls, so the time is O(n).
3. Distinct BST keys and their ordering make the construction unique. Reading and outputting n nodes requires Ω(n), yielding Θ(n).

Original paper, page 8

2 marks · MCQ
Report issue

Batch insertion into a binary heap

Heaps & Priority Queues

Question 47, GATE 2008: A binary heap contains n elements. Insert another n elements, not necessarily one at a time. What is the optimum total time?

(A) Θ(log n)
(B) Θ(n)
(C) Θ(n log n)
(D) Θ(n²)
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Append all n new elements to the existing n-element heap array, then run bottom-up BUILD-HEAP on the resulting 2n elements. Its total sift-down work is O(n), since the number of nodes of height h decreases geometrically and Σh/2h is constant.
2. Reading/storing n new elements requires Ω(n), so the optimum total is Θ(n), option B. The permission to insert them in a batch is crucial: n separate ordinary heap insertions can require Θ(n log n).

Original paper, page 8

2 marks · MCQ
Report issue

Pairwise linked-list value swaps

Arrays & Linked Lists

Question 62, GATE 2008: The list initially contains 1,2,3,4,5,6,7. What does it contain after this C function?
struct node { int value; struct node *next; };
void rearrange(struct node *list) {
 struct node *p,*q; int temp;
 if (!list || !list->next) return;
 p=list; q=list->next;
 while(q) {
  temp=p->value; p->value=q->value; q->value=temp;
  p=q->next; q=p ? p->next : 0;
 }
}

(A) 1,2,3,4,5,6,7
(B) 2,1,4,3,6,5,7
(C) 1,3,2,5,4,7,6
(D) 2,3,4,5,6,7,1
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. p starts at the first node and q at the second. The temporary variable exchanges their value fields; no next pointer is modified.
2. p=q->next advances to the next pair’s first node, and q becomes its successor when it exists. Thus pairs (1,2), (3,4), (5,6) swap.
3. The final node 7 has no partner, so q becomes null and the loop stops. The sequence is 2,1,4,3,6,5,7, B.

Original paper, page 12

1 mark · MCQ
Report issue

Maximum nodes at a given edge height

Tree Properties & Traversals

Question 12, GATE 2007: The height of a binary tree is the maximum number of edges on a root-to-leaf path. What is the maximum number of nodes at height h?
Options:
(A) 2^h−1
(B) 2^(h−1)−1
(C) 2^(h+1)−1
(D) 2^(h+1)
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. Approach. With edge height, the root is at depth zero. Count all levels including both level zero and level h, rather than counting only h levels.

2. Derivation and interpretation. At depth i a binary tree has at most 2i nodes. For edge height h, depths 0 through h sum to 1+2+...+2h=2h+1−1, C, attained by a perfect binary tree.

Original paper, page 3

1 mark · MCQ
Report issue

Three-node binary-tree shapes

Tree Properties & Traversals

Question 13, GATE 2007: How many different binary trees can be formed using three unlabeled nodes?
Options:
(A) 1
(B) 5
(C) 4
(D) 3
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Approach. Distinguish left and right child positions. There are four three-node chains (LL, LR, RL, RR) and one root with two children.

2. Derivation and interpretation. For ordered binary trees, let T(0)=1 and T(n)=sum T(i)T(n−1−i). Then T(1)=1,T(2)=2 and T(3)=2+1+2=5, B. Left and right child positions are distinguished, as in the standard binary-tree convention; unlabeled does not mean unordered.

Original paper, page 3

2 marks · MCQ
Report issue

Stack after the first multiplication

Stacks & Queues

Question 38, GATE 2007: Evaluate the postfix expression 8 2 3 ^ / 2 3 * + 5 1 * − using a stack; ^ denotes exponentiation. What are the top two stack elements, top first, immediately after the first * is evaluated?
Options:
(A) 6,1
(B) 5,7
(C) 3,2
(D) 1,5
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step through it (9 steps)

1. Approach. For each operand, push; for each binary operator, pop right operand then left operand, compute left op right, and push the result. Stop at the first multiplication rather than evaluating the whole expression.

2. Derivation and interpretation. Read 8,2,3, then exponentiation replaces 2,3 with 8; division replaces 8,8 with 1. Push 2 and 3; the first multiplication replaces them with 6. The stack is now [1,6] from bottom to top, so its top two elements are 6,1, A.

Original paper, page 9

2 marks · MCQ
Report issue

Postorder from inorder and preorder

Tree Properties & Traversals

Question 39, GATE 2007: A binary tree has inorder traversal d,b,e,a,f,c,g and preorder traversal a,b,d,e,c,f,g. What is its postorder traversal?
Options:
(A) d,e,b,f,g,c,a
(B) e,d,b,g,f,c,a
(C) e,d,b,f,g,c,a
(D) d,e,f,g,b,c,a
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. Approach. The first preorder item is the root. Its position in inorder separates left and right subtrees; recursively repeat, then output left subtree, right subtree, root.

2. Derivation and interpretation. Preorder starts with root a. Inorder splits the left subtree as d,b,e and the right as f,c,g. The remaining preorder makes b the left root with children d,e, and c the right root with children f,g. Postorder is d,e,b,f,g,c,a, option A.

Original paper, page 9

2 marks · MCQ
Report issue

Closed hashing with implicit linear probing

Hashing

Question 40, GATE 2007: An initially empty hash table has seven slots indexed 0–6 and h(x)=(3x+4) mod 7. Insert 1,3,8,10 in that order using “closed hashing” as stated in the source. Which final table is intended? A dash means an empty slot. The probing rule is not explicitly specified.
Options:
(A) [8,−,−,−,−,−,10]
(B) [1,8,10,−,−,−,3]
(C) [1,−,−,−,−,−,3]
(D) [1,10,8,−,−,−,3]
Tap to enlarge
Your answer
Answer & solution

Answer: B under linear probing (no official key was published)

1. Approach. Under linear probing, collisions advance one slot at a time with wraparound modulo 7. Compute each home position before inserting and never overwrite an occupied slot.

2. Derivation and interpretation. The hash values for 1,3,8,10 are 0,6,0,6. With linear probing, place 1 at 0 and 3 at 6;8 probes from 0 to 1;10 probes 6,0,1 and lands at 2. The table is [1,8,10,empty,empty,empty,3], B. Closed hashing/open addressing does not alone specify the probing sequence; quadratic or double hashing could differ, so linear probing is an explicit assumption rather than a stated guarantee.

Original paper, page 9

2 marks · MCQ
Report issue

Leaves and branching factor of a full n-ary tree

Tree Properties & Traversals

Question 43, GATE 2007: Here a complete n-ary tree means each node has exactly n children or none. It has I=10 internal nodes and L=41 leaves. Find n.
Options:
(A) 3
(B) 4
(C) 5
(D) 6
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. Approach. Count child edges once from the parent side and once using the identity edges=vertices−1 for a tree. Equating the counts eliminates the shape of the tree.

2. Derivation and interpretation. Count the edges in two ways. Each of the I internal nodes contributes exactly n child edges, while a tree with I+L vertices has I+L−1 edges. Thus nI=I+L−1 and n=(10+41−1)/10=5 (C). The question calls this complete, but explicitly defines the full n-ary property, which is all the calculation needs.

Original paper, page 10

2 marks · MCQ
Report issue

Recursive leaf counting in a binary tree

Tree Properties & Traversals

Question 46, GATE 2007: CellNode represents a binary-tree node. What does GetValue return when called on the root?
struct CellNode {
    struct CellNode *leftChild;
    int element;
    struct CellNode *rightChild;
};
int GetValue(struct CellNode *ptr) {
    int value=0;
    if(ptr!=NULL) {
        if(ptr->leftChild==NULL && ptr->rightChild==NULL)
            value=1;
        else value=value+GetValue(ptr->leftChild)+GetValue(ptr->rightChild);
    }
    return value;
}
Options:
(A) Number of nodes
(B) Number of internal nodes
(C) Number of leaves
(D) Tree height
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. Approach. Check the two base cases: null contributes zero, and a node with no children contributes one. All other nodes merely add child results, so their own elements and depths are irrelevant.

2. Derivation and interpretation. GetValue returns zero for a null pointer, one when both children are null, and otherwise the sum of the values for the left and right subtrees. By induction on the tree, this counts precisely the leaves: an internal node adds no contribution of its own. Therefore C, the number of leaf nodes, is correct, including zero for an empty tree.

Original paper, page 11

2 marks · MCQ
Report issue

Binary search along the heap insertion path

Heaps & Priority Queues

Question 47, GATE 2007: Insert an element into an array-represented max heap of n elements. Use binary search along the path from the new leaf to the root to locate its insertion position. What is the asymptotic worst-case number of key comparisons?
Options:
(A) Θ(log₂ n)
(B) Θ(log₂ log₂ n)
(C) Θ(n)
(D) Θ(n log₂ n)
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Approach. The binary search is not across the entire array. It searches the sorted ancestor chain, whose length is logarithmic in n; take the logarithm of that length.

2. Derivation and interpretation. A complete binary heap has a root-to-new-leaf path containing Θ(log n) positions. Existing keys along this path are monotone because it is a max heap. Binary search among h=Θ(log n) positions uses Θ(log h)=Θ(log log n) key comparisons in the usual worst-case interpretation, so B. This is a bound on comparisons, not all insertion work: shifting keys along the path can still require Θ(log n) moves. Array indices allow an ancestor at a specified depth to be selected without doing key comparisons.

Original paper, page 11

1 mark · MCQ
Report issue

Finding the minimum in a max heap

Heaps & Priority Queues

Question 10, GATE 2006: What is the worst-case asymptotic time for finding the smallest of n numbers stored in a binary max-heap?
Options:
(A) Θ(n)
(B) Θ(log n)
(C) Θ(log log n)
(D) Θ(1)
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. A minimum occurs among the leaves. There are Θ(n) leaves and their values have no guaranteed mutual ordering.

2. Scanning them gives O(n) time; arbitrary leaf values require Ω(n) comparisons in the worst case. Therefore Θ(n), A.

3. Teaching check: A max-heap constrains each parent to be at least its children, so following children can only decrease values. Every internal node has some leaf descendant no larger than itself. However the roughly n/2 leaves have no ordering among themselves, so binary-search reasoning does not apply.

Original paper, page 2

1 mark · MCQ
Report issue

Worst array index for a binary tree

Tree Properties & Traversals

Question 13, GATE 2006: Store any n-node binary tree in a one-based array: root at X[1], left child of X[i] at X[2i], right child at X[2i+1]. What minimum array capacity guarantees room for every possible n-node tree?
Options:
(A) log₂n
(B) n
(C) 2n+1
(D) 2^n−1
Question 13, GATE 2006: Store any n-node binary tree in a one-based array: root at X[1], left child of X[i] at X[2i], right child at X[2i+1]. What minimum array capacity guarantees room for every possible n-node tree?
Options:
(A) log₂n
(B) n
(C) 2n+1
(D) 2^n−1
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Following right children produces indices 1,3,7,...,2n−1 for an n-node chain. No n-node tree has depth beyond n−1, whose largest possible index is 2n−1.

2. Therefore an array indexed from 1 must provide that many positions, D. This counts logical one-based entries, not an extra unused C array index 0.

3. Teaching check: A chain of only right children is the worst case, not a balanced tree. Repeatedly applying i↦2i+1 from i=1 gives iₖ=2k+1−1 at depth k. The last of n nodes therefore occupies index 2n−1, although only n positions contain actual nodes.

Original paper, page 2

2 marks · MCQ
Report issue

Push and pop counts for a two-stack queue

Stacks & Queues

Question 49, GATE 2006: An initially empty queue is implemented using stacks S1,S2:
insert(Q,x): push(S1,x).
delete(Q): if S2 is empty, then if S1 is empty report empty and return; otherwise repeatedly pop S1 and push that item onto S2 until S1 is empty. Finally pop S2.
Perform n inserts and m≤n delete calls in arbitrary order. Let x be the total pushes and y the total pops on both stacks. Which printed bound holds for every n,m? Both reproductions use the strict upper bound x<2n; successful deletions are not explicitly guaranteed.
Options:
(A) n+m≤x<2n and 2m≤y≤n+m
(B) n+m≤x<2n and 2m≤y≤2n
(C) 2m≤x<2n and 2m≤y≤n+m
(D) 2m≤x<2n and 2m≤y≤2n
Question 49, GATE 2006: An initially empty queue is implemented using stacks S1,S2:
insert(Q,x): push(S1,x).
delete(Q): if S2 is empty, then if S1 is empty report empty and return; otherwise repeatedly pop S1 and push that item onto S2 until S1 is empty. Finally pop S2.
Perform n inserts and m≤n delete calls in arbitrary order. Let x be the total pushes and y the total pops on both stacks. Which printed bound holds for every n,m? Both reproductions use the strict upper bound x<2n; successful deletions are not explicitly guaranteed.
Options:
(A) n+m≤x<2n and 2m≤y≤n+m
(B) n+m≤x<2n and 2m≤y≤2n
(C) 2m≤x<2n and 2m≤y≤n+m
(D) 2m≤x<2n and 2m≤y≤2n
Tap to enlarge
Your answer
Answer & solution

Answer: No universally correct printed option (no official key was published)

1. Let t be the number of items moved from S1 to S2 and d the number of successful deletes. Then x=n+t pushes and y=t+d pops, with d≤t≤n.

2. If all m deletes succeed, d=m, so n+m≤x≤2n and 2m≤y≤n+m. These are the tight intended bounds.

3. The paper prints x<2n in all four options, which fails when all n inserts precede a delete: t=n and x=2n. Furthermore arbitrary ordering permits deletes on an empty queue; then d need not equal m and the printed lower bounds can fail.

4. If < were repaired to ≤ and successful deletions assumed, A states the tight bounds, but other looser options would also be true. Do not treat this the paper as a sound unique-answer MCQ without checking a better source.

6. A minimal counterexample is one insert followed by one delete: n=m=1 and x=y=2. This does not establish what the official original printed.

7. Teaching check: Every inserted item is pushed onto S1 exactly once and transferred to S2 at most once. A successful deletion adds one S2 pop. Counting these lifecycle events gives exact formulas before bounds are imposed; testing n=m=1 immediately exposes the printed strict inequality.

Original paper, page 7

2 marks · MCQ
Report issue

Valid array representation of ternary max-heap

Heaps & Priority Queues

Question 76, GATE 2006: A ternary max-heap is stored level-by-level, left-to-right, in a zero-based array. Root is a[0]; children of i are 3i+1,3i+2,3i+3. Insert by appending then moving upward until the parent is at least as large. Which array is a valid heap?
Options:
(A) [1,3,5,6,8,9]
(B) [9,6,3,1,8,5]
(C) [9,3,6,8,5,1]
(D) [9,5,6,8,3,1]
Question 76, GATE 2006: A ternary max-heap is stored level-by-level, left-to-right, in a zero-based array. Root is a[0]; children of i are 3i+1,3i+2,3i+3. Insert by appending then moving upward until the parent is at least as large. Which array is a valid heap?
Options:
(A) [1,3,5,6,8,9]
(B) [9,6,3,1,8,5]
(C) [9,3,6,8,5,1]
(D) [9,5,6,8,3,1]
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. In a zero-based ternary heap, children of i are 3i+1,3i+2,3i+3. For D=[9,5,6,8,3,1], root 9 dominates 5,6,8 and node 5 dominates children 3,1.

2. A fails at the root; B has parent 6 with child 8; C has parent 3 with child 5. Only D is a valid max-heap.

3. Teaching check: Heap order is a parent-child condition, not full sorting. For six entries only root 0 and node 1 have children; checking these is sufficient. Option D’s 8 may exceed node 1’s 5 because they are siblings, so that comparison imposes no restriction.

Original paper, page 12

2 marks · MCQ
Report issue

Four insertions into ternary heap

Heaps & Priority Queues

Question 77, GATE 2006: A ternary max-heap is stored level-by-level, left-to-right, in a zero-based array. Root is a[0]; children of i are 3i+1,3i+2,3i+3. Insert by appending then moving upward until the parent is at least as large. Start from the valid heap [9,5,6,8,3,1] and insert 7,2,10,4 in that order. What final array results?
Options:
(A) [10,7,9,8,3,1,5,2,6,4]
(B) [10,9,8,7,6,5,4,3,2,1]
(C) [10,9,4,5,7,6,8,2,1,3]
(D) [10,8,6,9,7,2,3,4,1,5]
Question 77, GATE 2006: A ternary max-heap is stored level-by-level, left-to-right, in a zero-based array. Root is a[0]; children of i are 3i+1,3i+2,3i+3. Insert by appending then moving upward until the parent is at least as large. Start from the valid heap [9,5,6,8,3,1] and insert 7,2,10,4 in that order. What final array results?
Options:
(A) [10,7,9,8,3,1,5,2,6,4]
(B) [10,9,8,7,6,5,4,3,2,1]
(C) [10,9,4,5,7,6,8,2,1,3]
(D) [10,8,6,9,7,2,3,4,1,5]
Question 77, GATE 2006: A ternary max-heap is stored level-by-level, left-to-right, in a zero-based array. Root is a[0]; children of i are 3i+1,3i+2,3i+3. Insert by appending then moving upward until the parent is at least as large. Start from the valid heap [9,5,6,8,3,1] and insert 7,2,10,4 in that order. What final array results?
Options:
(A) [10,7,9,8,3,1,5,2,6,4]
(B) [10,9,8,7,6,5,4,3,2,1]
(C) [10,9,4,5,7,6,8,2,1,3]
(D) [10,8,6,9,7,2,3,4,1,5]
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step through it (9 steps)

1. Start with [9,5,6,8,3,1]. Insert 7 at index 6 and exchange with parent index 1, obtaining [9,7,6,8,3,1,5].

2. Insert 2 at index 7, whose parent 6 is already larger: [9,7,6,8,3,1,5,2]. Insert 10 at index 8, exchange with parent index 2 (6), then root 9, obtaining [10,7,9,8,3,1,5,2,6].

3. Insert 4 at index 9 under parent 9, with no exchange. Final array [10,7,9,8,3,1,5,2,6,4], A.

4. Teaching check: The parent index is floor((i−1)/3). After appending 10 at index 8, its parent is index 2, then the root, so two upward swaps occur. Appending 4 at index 9 places it under the current 9 and requires no swap.

Original paper, page 12

1 mark · MCQ
Report issue

Abstract data type interface

Other / Mixed Topics

Question 2, GATE 2005: An abstract data type is: A an abstract class; B a type that cannot be instantiated; C a type used through its defined operations rather than arbitrary representation operations; D all of these.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

An ADT specifies values and the operations permitted on them while hiding representation. Clients use its defined interface, C. It is not identical to an abstract class and does not imply that values/instances cannot be created.

An ADT defines permitted values and operations independently of how data is stored. A stack, for example, offers push/pop without letting clients depend on array indices or linked-node layout. It can have instances and can be implemented in many languages, including languages without classes. Thus C describes abstraction; A and B confuse separate language mechanisms with the abstract specification.

Original paper, page 1

1 mark · MCQ
Report issue

Counting scores above fifty

Arrays & Linked Lists

Question 5, GATE 2005: Read 500 integer scores in [0, 100] and print frequencies of scores above 50. Best frequency storage? A array of 50 numbers; B array of 100; C array of 500; D dynamically allocated array of 550.
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Only scores 51 through 100 need counts, exactly 50 possible values. Maintain a 50-entry array initialized to zero and increment index score−51 whenever score>50. All 500 observations can be streamed without storage, so A.

The only reported scores are 51, 52,…, 100, exactly 50 possibilities. Allocate one counter for each and map a qualifying score s to index s−51. Increment its counter while reading; scores at most 50 need no stored frequency for the requested output. The program need not retain all 500 observations. This distinguishes number of possible output categories from number of input records.

Original paper, page 1

2 marks · MCQ
Report issue

Inorder traversal of a binary search tree

Binary Search & Balanced Trees

Question 33, GATE 2005: BST postorder is 10, 9, 23, 22, 27, 25, 15, 50, 95, 60, 40, 29. Candidate inorder A9, 10, 15, 22, 23, 25, 27, 29, 40, 50, 60, 95; B9, 10, 15, 22, 40, 50, 60, 95, 23, 25, 27, 29; C29, 15, 9, 10, 25, 22, 23, 27, 40, 60, 50, 95; D95, 50, 60, 40, 27, 23, 22, 25, 10, 9, 15, 29.
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Inorder traversal of a BST with distinct keys lists them in increasing order. Sorting the displayed key set gives 9, 10, 15, 22, 23, 25, 27, 29, 40, 50, 60, 95, option A. No full reconstruction from postorder is necessary.

For distinct keys in a BST, inorder visits every smaller key before the root and every larger key afterward, recursively producing the sorted key list. Sorting the supplied set gives A. There is no need to reconstruct the full shape from postorder unless the task asks for structure; postorder here merely specifies which keys are present.

Original paper, page 4

2 marks · MCQ
Report issue

Inserting into a max heap

Heaps & Priority Queues

Question 34, GATE 2005: Max-heap level order 10, 8, 5, 3, 2 receives 1 then 7. New level order? A10, 8, 7, 5, 3, 2, 1; B10, 8, 7, 2, 3, 1, 5; C10, 8, 7, 1, 2, 3, 5; D10, 8, 7, 3, 2, 1, 5.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step through it (5 steps)

Append 1 as the sixth element; its parent 5 is larger, so no swap occurs. Append 7 as the seventh element; swap it with parent 5, but stop below root 10. The resulting level order is 10, 8, 7, 3, 2, 1, 5, D.

Appending 1 puts it under parent 5 and requires no upward swap. Appending 7 puts it as the other child of 5;7 exceeds 5, so swap them. Its new parent is 10, which is larger, ending the repair. Other nodes remain where they were, yielding 10, 8, 7, 3, 2, 1, 5. A heap is not a sorted array; sorting the level order would unnecessarily rearrange nodes.

Original paper, page 4

2 marks · MCQ
Report issue

Binary search trees on four keys

Binary Search & Balanced Trees

Question 35, GATE 2005: How many BSTs can be formed from four distinct keys? A5; B14; C24; D42.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

For distinct ordered keys, the number of BST shapes is the Catalan number C4. With C0=1, C1=1, C2=2, C3=5, the root split gives C4=1×5+1×2+2×1+5×1=14, B.

Choose each possible root rank and multiply the independent choices for left and right subtrees. Catalan recurrence C_n=Σ C_i C_(n−1−i), with C0=1, gives C1=1, C2=2, C3=5 and C4=5+2+2+5=14. This counts BST shapes with the sorted keys forced into inorder order, not arbitrary permutations of labels, so 4!=24 is not the answer.

Original paper, page 4

2 marks · MCQ
Report issue

Leaves in a full k-ary tree

Tree Properties & Traversals

Question 36, GATE 2005: A finite full k-ary tree has n internal nodes, each with exactly k children. Number of leaves? A nk; B(n−1)k+1; C n(k−1)+1; D n(k−1).
Question 36, GATE 2005: A finite full k-ary tree has n internal nodes, each with exactly k children. Number of leaves? A nk; B(n−1)k+1; C n(k−1)+1; D n(k−1).
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

If there are n internal nodes and L leaves, the number of parent-child edges is kn. Any finite tree also has n+L−1 edges. Equating gives L=n(k−1)+1, C. The premise is that every internal node has exactly k children, not merely at most k.

Count the same edges in two ways. Every internal node contributes k outgoing parent-child edges, for kn. Any tree on n+L total nodes has n+L−1 edges. Equating and solving yields L=kn−n+1=n(k−1)+1. This method does not require every leaf to have the same depth; the exact-k-child premise is what matters.

Original paper, page 4

1 mark · MCQ
Report issue

Two stacks sharing an array

Stacks & Queues

Question 3, GATE 2004: Two stacks share A[1..MAXSIZE], growing from opposite ends. top1<top2 identify their topmost occupied cells. What full condition uses the available space efficiently?
Options:
(A) top1=MAXSIZE/2 AND top2=MAXSIZE/2+1
(B) top1+top2=MAXSIZE
(C) top1=MAXSIZE/2 OR top2=MAXSIZE
(D) top1=top2−1
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. The unused positions lie strictly between top1 and top2. There is no free position exactly when the tops are adjacent, top1=top2−1, D.

2. This lets either stack use all available space instead of reserving half the array.

3. Teaching check: The number of unused cells is top2−top1−1. Setting this to zero immediately gives the full condition. A fixed half-array boundary can falsely declare overflow while the other stack leaves unused cells, defeating the purpose of sharing capacity.

Original paper, page 1

1 mark · MCQ
Report issue

Height after binary-search-tree insertions

Binary Search & Balanced Trees

Question 4, GATE 2004: Insert 10,1,3,5,15,12,16, in that order, into an empty binary search tree. What is its height, defined as the maximum edge distance from root to a leaf?
Options:
(A) 2
(B) 3
(C) 4
(D) 6
Question 4, GATE 2004: Insert 10,1,3,5,15,12,16, in that order, into an empty binary search tree. What is its height, defined as the maximum edge distance from root to a leaf?
Options:
(A) 2
(B) 3
(C) 4
(D) 6
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Step through it (9 steps)

1. Inserting10,1,3,5 produces the chain 10→1→3→5 on the left side. The remaining 15,12,16 form a right subtree rooted 15 with two children.

2. The deepest leaf 5 is three edges from 10, so the stated edge-distance height is 3, B.

3. Teaching check: The complete parent-child structure is 10:(left 1,right 15), 1:(right 3), 3:(right 5), 15:(left 12,right 16). The deepest path has four vertices but three edges. Distinguishing edge height from node count eliminates the off-by-one distractor.

Original paper, page 1

1 mark · MCQ
Report issue

Balanced parentheses

Stacks & Queues

Question 5, GATE 2004: Which listed data structure is best for checking whether parentheses in an arithmetic expression are balanced?
Options:
(A) Queue
(B) Stack
(C) Tree
(D) List
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. A stack matches each closing delimiter with the most recently unmatched opening delimiter. Reject an unmatched/mismatched close and accept only if the stack is empty at the end.

2. Thus B. With only one kind of parenthesis a counter is sufficient, but stack is the appropriate listed general delimiter-matching structure.

3. Teaching check: On an opening parenthesis, push it; on a closing one, require and pop its matching opener. The last-in-first-out rule handles nesting such as (()()). A FIFO queue does not retain the most recently opened delimiter at its removal end.

Original paper, page 1

1 mark · MCQ
Report issue

Level-order traversal

Tree Properties & Traversals

Question 6, GATE 2004: Starting at the root, which traversal produces level order in a rooted tree?
Options:
(A) Preorder
(B) Inorder
(C) Depth-first search
(D) Breadth-first search
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Breadth-first search uses a queue to visit the root, then all children, then their children, and so on. This is precisely level order, D; depth-first traversals do not generally preserve depth order.

2. Teaching check: Begin with just the root in a queue. Repeatedly dequeue a vertex and enqueue its children. Children of a depth-d vertex are enqueued behind all remaining depth-d vertices, so no depth-(d+1) vertex is processed prematurely.

Original paper, page 1

1 mark · MCQ
Report issue

Hash collisions under modulo ten

Hashing

Question 7, GATE 2004: Hash the input 4322,1334,1471,9679,1989,6171,6173,4199 using h(x)=x mod 10. Which statements hold? (1) 9679,1989,4199 collide. (2) 1471,6171 collide. (3) All inputs hash to the same value. (4) Every input has a different hash value.
Options:
(A) 1 only
(B) 2 only
(C) 1 and 2 only
(D) 3 or 4
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. The hash is the last decimal digit.9679,1989,4199 all map to 9, while 1471 and 6171 both map to 1. The remaining values map to 2,4,3.

2. Thus statements 1 and 2 only are true, C.

3. Teaching check: The eight hash values in input order are 2,4,1,9,9,1,3,9. This explicit list both verifies the two claimed collisions and refutes the “all equal” and “all different” alternatives. Collision means equal hash output, not equal original keys.

Original paper, page 1

2 marks · MCQ
Report issue

Traversal pairs uniquely determining a binary tree

Tree Properties & Traversals

Question 35, GATE 2004: For an unrestricted binary tree with distinct node labels, which pairs of label sequences determine the tree uniquely? (i) preorder and postorder; (ii) inorder and postorder; (iii) preorder and inorder; (iv) level order and postorder.
Options:
(A) i only
(B) ii and iii
(C) iii only
(D) iv only
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. With distinct node labels, inorder plus preorder identifies the root then splits both subtrees recursively; inorder plus postorder does the same using the final element as root. Thus ii and iii, B.

2. A root with one left child versus one right child has identical preorder, postorder and level order, so the other pairs do not suffice for unrestricted binary trees. Distinct labels are the conventional assumption.

3. Teaching check: For a concrete ambiguity, a root A with sole left child B and a root A with sole right child B both have preorder A,B, postorder B,A and level order A,B. Inorder distinguishes B,A from A,B, explaining why it is indispensable among the offered pairs.

Original paper, page 5

2 marks · MCQ
Report issue

One-pointer circular queue

Stacks & Queues

Question 36, GATE 2004: A queue is represented by a singly linked circular list: front→successive queue nodes→rear→front. One pointer p is available. Where should p point so both enqueue and dequeue take constant time?
Options:
(A) Rear node
(B) Front node
(C) Impossible with one pointer
(D) Node next to front
Question 36, GATE 2004: A queue is represented by a singly linked circular list: front→successive queue nodes→rear→front. One pointer p is available. Where should p point so both enqueue and dequeue take constant time?
Options:
(A) Rear node
(B) Front node
(C) Impossible with one pointer
(D) Node next to front
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. Keep p at the rear, whose next pointer is the front. Enqueue inserts after p and advances p to the new rear; dequeue removes p.next, with a special empty result for a singleton.

2. Both take constant time, A. Keeping only the front would require finding its predecessor to update the rear link.

3. Teaching check: For enqueue, set new.next=p.next, then p.next=new and p=new. For dequeue, remove p.next and advance that link; if it was the sole node, mark the queue empty. A circular rear pointer therefore exposes both ends without a predecessor scan.

Original paper, page 5

2 marks · MCQ
Report issue

Heap built by successive insertions

Heaps & Priority Queues

Question 37, GATE 2004: Insert 32,15,20,30,12,25,16 one at a time into an empty binary max-heap, using upward restoration after each insertion. Which resulting heap is obtained? The four source diagrams are encoded below as level-order arrays (root first, left-to-right at each level).
Options:
(A) [32,30,25,15,12,20,16]
(B) [32,25,30,12,15,20,16]
(C) [32,30,25,15,12,16,20]
(D) [32,25,30,12,15,16,20]
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step through it (11 steps)

1. Insert32,15,20, then 30 bubbles above 15, giving[32,30,20,15]. Insert12 unchanged.

2. Insert25 bubbles above 20, giving[32,30,25,15,12,20];16 remains under 25. Final level order is 32,30,25,15,12,20,16, diagram A.

3. Teaching check: Insertion order matters: the final heap need not be the one obtained by bottom-up heapifying the array or sorting its values. Inserting 30 swaps it above 15; inserting 25 swaps it above 20. All remaining parent-child inequalities already hold.

Original paper, page 5

2 marks · MCQ
Report issue

Postfix with right-associative exponentiation

Stacks & Queues

Question 38, GATE 2004: Operators +,−,× are left-associative and ^ is right-associative. Precedence from highest to lowest is ^,×,+,−. Find postfix for a+b×c−d^e^f. Tokens in each alternative are separated for readability.
Options:
(A) a b c × + d e f ^ ^ −
(B) a b c × + d e ^ f ^ −
(C) a b + c × d − e ^ f ^
(D) − + a × b c ^ ^ d e f
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step through it (13 steps)

1. The grouping is(a+(b×c))−(de^f). Write each subtree’s operands before its operator: a b c × + d e f ^ ^ −.

2. Thus A. Right associativity places the ef operation before raising d to that result.

3. Teaching check: The parse first builds b×c and ef, then de^f, then a+(b×c), and finally subtraction. Postorder traversal emits operands before operators. The alternative with d e ^ f ^ instead encodes (de)f and violates right associativity.

Original paper, page 5

2 marks · MCQ
Report issue

Set operations on unsorted linked lists

Arrays & Linked Lists

Question 40, GATE 2004: Each set is an unsorted linked list. Under direct list algorithms, which operations among union, intersection, membership and cardinality are slowest?
Options:
(A) Union only
(B) Intersection and membership
(C) Membership and cardinality
(D) Union and intersection
Tap to enlarge
Your answer
Answer & solution

Answer: D for direct list algorithms (no official key was published)

1. Membership scans a list in O(n), and cardinality is O(n) by traversal (or O(1) if stored). For union/intersection of two unsorted lists of comparable size, direct algorithms test each element against the other list, taking Θ(n²) worst case while avoiding duplicates in the union.

2. Thus union and intersection, D. Auxiliary hashing or sorting can improve these operations; the comparison assumes direct operations on the stated unsorted-list representation without such an index.

3. Teaching check: For two length-n lists, compare each candidate against up to n elements of the other list. That nested search costs Θ(n²), unlike a single membership or counting scan. Union must eliminate duplicates rather than merely concatenate the lists.

Original paper, page 6

2 marks · MCQ
Report issue

Recursive binary-tree height

Tree Properties & Traversals

Question 43, GATE 2004: Consider a binary-tree node with fields leftChild, element and rightChild, and this function (max returns the larger argument):
int DoSomething(struct CellNode *ptr) {
  int value=0;
  if(ptr!=NULL) {
    if(ptr->leftChild!=NULL)
      value=1+DoSomething(ptr->leftChild);
    if(ptr->rightChild!=NULL)
      value=max(value,1+DoSomething(ptr->rightChild));
  }
  return value;
}
What is returned when ptr is the root of a nonempty tree?
Options:
(A) Number of leaf nodes
(B) Number of nodes
(C) Number of internal nodes
(D) Height of tree
Question 43, GATE 2004: Consider a binary-tree node with fields leftChild, element and rightChild, and this function (max returns the larger argument):
int DoSomething(struct CellNode *ptr) {
  int value=0;
  if(ptr!=NULL) {
    if(ptr->leftChild!=NULL)
      value=1+DoSomething(ptr->leftChild);
    if(ptr->rightChild!=NULL)
      value=max(value,1+DoSomething(ptr->rightChild));
  }
  return value;
}
What is returned when ptr is the root of a nonempty tree?
Options:
(A) Number of leaf nodes
(B) Number of nodes
(C) Number of internal nodes
(D) Height of tree
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. A leaf returns zero. A node with a child takes one plus that child’s recursively computed value; with two children it takes the maximum.

2. Induction gives the maximum number of edges from the node to a descendant leaf, i.e. height measured in edges. The null check returns zero but no missing child adds an edge.

3. The code does not count nodes or leaves.

4. Teaching check: A singleton tree returns zero, immediately excluding both total-node and leaf counts. A two-edge chain returns two. The recursive maximum chooses the deepest child path, while adding one accounts for the edge from the current node to that child.

Original paper, page 6

1 mark · MCQ
Report issue

Catalan recurrence for binary search trees

Binary Search & Balanced Trees

Question 6, GATE 2003: Let T(n) count binary search trees on n distinct keys. In T(n)=sum from k=1 to n of T(k−1)T(x), what is x? A. n−k+1; B. n−k; C. n−k−1; D. n−k−2.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Partition all trees by their root’s rank k. No key greater than the root may be in its left subtree, so the sizes are forced rather than chosen. For each left shape any right shape is allowed; multiply within a fixed k and sum over the disjoint root choices. Empty subtrees contribute T(0)=1.

2. If the root is the kth smallest key, its left subtree contains k−1 keys and its right subtree n−k. Their shapes can be chosen independently, giving T(k−1)T(n−k). Thus the missing argument x=n−k, B, with T(0)=1.

Original paper, page 1

1 mark · MCQ
Report issue

Inorder traversal of inserted keys

Binary Search & Balanced Trees

Question 19, GATE 2003: Insert 7,5,1,8,3,6,0,9,4,2, in this order, into an initially empty binary search tree using ordinary numerical order. What is its inorder traversal? A. 7,5,1,0,3,2,4,6,8,9; B. 0,2,4,3,1,6,5,9,8,7; C. 0,1,2,3,4,5,6,7,8,9; D. 9,8,6,4,2,3,0,1,5,7.
Question 19, GATE 2003: Insert 7,5,1,8,3,6,0,9,4,2, in this order, into an initially empty binary search tree using ordinary numerical order. What is its inorder traversal? A. 7,5,1,0,3,2,4,6,8,9; B. 0,2,4,3,1,6,5,9,8,7; C. 0,1,2,3,4,5,6,7,8,9; D. 9,8,6,4,2,3,0,1,5,7.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Step through it (23 steps)

1. At each node, all left-subtree keys are smaller and all right-subtree keys larger. Inorder recursively visits left subtree, root, right subtree, so this invariant sorts the output. The insertion order determines tree shape but cannot change this ordering property.

2. An inorder traversal of a BST visits its distinct keys in increasing order, independently of insertion order. The given keys are exactly 0 through 9, so the sequence is 0,1,2,3,4,5,6,7,8,9, C.

Original paper, page 2

1 mark · MCQ
Report issue

Fixed-rank selection from a min heap

Heaps & Priority Queues

Question 23, GATE 2003: A min-heap has n elements, with its smallest at the root. For n≥7, what time is sufficient to find the seventh smallest element, as a function of n? A. Θ(n log n); B. Θ(n); C. Θ(log n); D. Θ(1).
Question 23, GATE 2003: A min-heap has n elements, with its smallest at the root. For n≥7, what time is sufficient to find the seventh smallest element, as a function of n? A. Θ(n log n); B. Θ(n); C. Θ(log n); D. Θ(1).
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. The candidate frontier contains the roots of all unexplored subheaps. Heap order makes its minimum the smallest unseen element. Extract that node and add at most its two children, preserving the invariant. After seven iterations the frontier and work are bounded by constants independent of n.

2. Maintain a small candidate min-priority queue initially containing the root. Repeatedly remove its minimum and insert that node’s children; after seven removals the extracted value is seventh smallest. Only a constant number of nodes and candidate operations are used because rank 7 is fixed, hence Θ(1) with respect to n, D, assuming n≥7. Repeatedly deleting from the original n-element heap is unnecessarily expensive.

Original paper, page 3

2 marks · MCQ
Report issue

Ordered set supporting minimum deletion and unique insertion

Binary Search & Balanced Trees

Question 63, GATE 2003: A set of n integers must support (I) deleting its smallest element and (II) inserting an element only if it is not already present, each in O(log n) time. Which structure suffices?
A. A heap, but not a balanced binary search tree
B. A balanced binary search tree, but not a heap
C. Both a balanced binary search tree and a heap
D. Neither
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. A balanced binary search tree has height O(log n). Follow left children to the minimum and delete/rebalance in O(log n). Search for a proposed key and, if absent, insert/rebalance along one root-to-leaf path in O(log n).
2. A min-heap can delete its root and sift down in O(log n), and can insert a known-new key in O(log n).
3. However, a heap is only partially ordered. Testing whether an arbitrary key already appears can require inspecting Θ(n) positions; insertion-if-absent includes that test.
4. Thus the balanced tree alone meets both requirements, B. A heap augmented with a separate search index is not the plain heap being compared.

Solution: A balanced binary search tree supports membership search, insertion, and deletion of its minimum in O(log n) worst-case time. A plain heap supports minimum deletion and unrestricted insertion in O(log n), but checking whether an arbitrary proposed value is already present may require Θ(n) comparisons. Therefore the uniqueness requirement rules out the heap alone, leaving B. Augmenting a heap with a separate membership structure is outside the listed plain-structure comparison.

Original paper, page 9

2 marks · MCQ
Report issue

Average residence time in a push-then-pop stack

Stacks & Queues

Question 64, GATE 2003: An initially empty stack of capacity n≥1 receives pushes of 1,...,n in order, followed by n pops. Each push/pop takes X seconds; a gap of Y seconds separates the end of each operation from the start of the next. The stack-life of m is the interval from the end of push(m) to the start of the pop removing m. What is the average stack-life?
A. n(X+Y)
B. 3Y+2X
C. n(X+Y)−X
D. Y+2X
Question 64, GATE 2003: An initially empty stack of capacity n≥1 receives pushes of 1,...,n in order, followed by n pops. Each push/pop takes X seconds; a gap of Y seconds separates the end of each operation from the start of the next. The stack-life of m is the interval from the end of push(m) to the start of the pop removing m. What is the average stack-life?
A. n(X+Y)
B. 3Y+2X
C. n(X+Y)−X
D. Y+2X
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. LIFO means m is removed after the n−m elements above it. Between the two specified endpoints lie n−m later pushes and n−m earlier pops, a total of 2(n−m) complete operations.
2. There is one more gap than intervening operations, so life(m)=2(n−m)X+[2(n−m)+1]Y. The push of m and its own pop are excluded by the endpoint definition.
3. Average n−m over m=1,...,n: [0+...+(n−1)]/n=(n−1)/2. Substitution gives (n−1)X+nY=n(X+Y)−X.
4. Hence C. For n=1, life is just Y, confirming the endpoint accounting.

Solution: For item m, there are n−m later pushes and n−m earlier pops between the end of push(m) and the start of its pop. Those 2(n−m) complete intervening operations cost 2(n−m)X and the 2(n−m)+1 gaps cost [2(n−m)+1]Y. Average n−m over m=1,…,n is (n−1)/2, so the mean is (n−1)X+nY=n(X+Y)−X, option C. For n=1 it correctly reduces to the single gap Y.

Original paper, page 9

2 marks · MCQ
Report issue

Inserting a key in a 2–3–4 tree

B-Trees & Multiway Search Trees

Question 65, GATE 2003: A 2–3–4 tree (B-tree of minimum degree 2) stores letters in alphabetical order. Its root is [L,P,U], with leaf children [B,H,I], [N], [Q,T], [V,X,Z] from left to right. GateForum asks for the result of inserting G; that request is omitted in GFG. Candidate trees (children listed left to right) are:
A. Root [P]; internal children [G,L] and [U]. Their leaf children are [B],[H,I],[N] and [Q,T],[V,X,Z].
B. Root [P]; internal children [H,L] and [U]. Their leaf children are [B,G],[I],[N] and [Q,T],[V,X,Z].
C. Root [I,P,U], with leaves [B,G,H],[L,N],[Q,T],[V,X,Z].
D. None of the above.
Use standard split-before-descent insertion to select the conventional result; the statement does not explicitly specify its insertion policy.
Tap to enlarge
Your answer
Answer & solution

Answer: B under standard split-before-descent insertion (no official key was published)

1. A minimum-degree-2 node holds at most three keys. The initial root is full, so split it before descending: promote P to a new root; its children hold [L] and [U]. The old four leaves are divided two per child.
2. G<P and G<L, so descend toward [B,H,I]. This child is full too. Promote its median H into [L], giving [H,L], and replace the leaf by [B] and [I].
3. G<H, so insert it into [B] to obtain [B,G]. The other leaves stay [I],[N],[Q,T],[V,X,Z]. These are exactly the links in B.
4. This is algorithm-dependent: A can arise under a bottom-up split choice, and C under redistribution. Neither the invariants alone nor the incomplete the wording uniquely force B.

Under standard top-down B-tree insertion, first split the full root [L,P,U], promoting P and giving children [L] and [U]. Descending left, split its full child [B,H,I], promoting H into [L] to obtain [H,L] and leaves [B],[I],[N]. Insert G into [B], giving [B,G]. The result is option B, with root [P], left child [H,L] and right child [U]. A different valid insertion policy can produce another valid B-tree: A follows suitable bottom-up split choices, and C uses redistribution to a sibling. Consequently B is the conventional algorithmic answer, not a uniquely forced tree from the B-tree invariants alone.

Original paper, page 9

2 marks · MCQ
Report issue

Recursive linked-list sortedness predicate

Arrays & Linked Lists

Question 90, GATE 2003: Consider a finite, well-formed singly linked list and the function:
struct item { int data; struct item *next; };
int f(struct item *p) {
  return (p==NULL) || (p->next==NULL) ||
         ((p->data<=p->next->data) && f(p->next));
}
f returns 1 if and only if:
A. The list is empty or has exactly one element
B. List data are in nondecreasing order
C. List data are in nonincreasing order
D. Not all elements have the same data value
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. If p is NULL, the first OR operand is true; short-circuiting prevents any dereference. If p names the last node, the second operand is true and prevents accessing a nonexistent next node.
2. Otherwise both base tests are false, so success requires p.data≤p.next.data and a successful recursive check of the suffix.
3. Induct on list length. Empty/singleton lists are nondecreasing. For length at least two, the suffix is nondecreasing exactly when the recursion succeeds, and the current comparison places the first element before that sorted suffix. Thus all adjacent inequalities hold exactly when f returns true.
4. The predicate is nondecreasing order, B; equal values are allowed. Longer sorted lists refute A, and the comparison direction refutes C. Cyclic lists are outside the ordinary finite-list assumption.

Solution: The empty list and a one-node list return true. For any longer list, short-circuit evaluation checks data at the current node≤data at the next node and then recursively verifies the suffix. By induction, the result is true exactly when every adjacent pair is in nondecreasing order, option B. The initial null checks protect the pointer dereferences. This assumes the ordinary finite, well-formed, acyclic linked-list input; on a cycle recursion need not terminate.

Original paper, page 13

1 mark · MCQ
Report issue

Worst-case search in a linked list

Arrays & Linked Lists

Question 1.5, GATE 2002: How many comparisons are needed in the worst case to find a specified element in a singly linked list with n elements?
(A) log₂ n; (B) n/2; (C) log₂ n − 1; (D) n.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step 1: Identify a worst-case input.

Step 2: Put the target in the final node. Before examining that node, none of the earlier comparisons succeeds, so there are n−1 failed comparisons and one successful comparison. If the target is absent there are n failed comparisons instead. Binary-search logarithmic bounds require positional access and ordering not supplied here; n/2 is not a worst-case bound.

Conclusion: An absent key or a key only at the final node requires examining all n nodes. Each node entails one comparison with the search key, so the worst case is n, D.

Original paper, page 1

2 marks · MCQ
Report issue

Height of a weight-balanced binary tree

Binary Search & Balanced Trees

Question 2.12, GATE 2002: A weight-balanced binary tree is defined so that, at every node, the left subtree’s node count is at least half and at most twice the right subtree’s count. Which expression best describes its maximum possible height with n nodes, counting nodes along the root-to-farthest-leaf path?
(A) log₂ n; (B) log₂⁄₃ n; (C) log₃ n; (D) log₃⁄₂ n.
Tap to enlarge
Your answer
Answer & solution

Answer: D as the standard growth-bound expression (no official key was published)

Step 1: Use the heavier child on a deepest path.

Step 2: If child sizes are a≥b, the weight constraint gives a≤2b. Since a+b=n−1, this implies a≤2(n−1)/3. Repeating the inequality along a path yields geometric shrinkage and a logarithmic height. Integer rounding prevents the option from being an exact height formula; its role is to express the extremal shrinkage factor rather than a literal answer for every small n.

Conclusion: A child subtree contains at most 2(n−1)/3 nodes. Following a deepest branch therefore shrinks the remaining size by at least a constant factor 3/2, yielding height at most log3/2n+O(1). Maximally skewed admissible weight splits attain the same leading logarithmic growth, so D is the conventional expression. The displayed logarithm is a growth bound, not an exact integer height for every n; rounding and admissible tree sizes matter.

Original paper, page 5

2 marks · MCQ
Report issue

Stack space for expression evaluation

Stacks & Queues

Question 2.19, GATE 2002: To evaluate an expression containing no embedded function calls, which claim is correct?
(A) One stack suffices.
(B) Two stacks are required.
(C) The number of required stacks equals the expression-tree height.
(D) A Turing machine is required in the general case.
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step 1: Walk through a one-stack evaluation.

Step 2: For postfix tokens a b + c *, push a then b, pop them and push a+b, then push c, and finally replace the top two values with(a+b)c. The same procedure handles arbitrary finite postfix expressions by induction on the expression tree. Extra stacks can help conversion or implementation, but are not inherently required for evaluation.

Conclusion: For a postfix representation, push operands and replace the required top operands by the result whenever an operator is encountered. One evaluation stack suffices for any finite expression tree without embedded calls, A. Infix parsing can use a combined stack representation or first produce postfix; two separate stacks are a convenient implementation, not a necessity.

Original paper, page 5

Descriptive
Report issue

Enumerate binary trees with fixed preorder

Tree Properties & Traversals

Question 6, GATE 2002: Draw every binary tree with exactly three labeled nodes A, B, C for which preorder traversal visits C, B, A in that order.
Tap to enlarge
Shared context

Find every ordered binary tree containing exactly the distinct labels A, B, C whose preorder sequence is C,B,A. Left and right child positions are distinguished.

Answer & solution

Answer: Exactly 5 ordered binary trees (no official key was published)

1. Use the first preorder symbol to fix the root. Preorder visits root, then left subtree, then right subtree. Therefore every requested tree must have C at its root.

2. Partition the two remaining nodes between C’s subtrees. The possible left/right subtree sizes are (2,0), (0,2), and (1,1). These cases exhaust the possibilities because there are exactly two nodes besides C.

3. Handle the two single-subtree cases. For sizes (2,0), B is C’s left child, and A is either B’s left child or B’s right child: two trees. For sizes (0,2), B is C’s right child, and A again has two child positions: two more trees. B must precede A because their subtree’s preorder must be B,A.

4. Handle sizes (1,1). Preorder visits the entire left subtree before the right, so the left child is B and the right child is A: one tree. Reversing those children would give C,A,B and is not allowed.

5. Draw the resulting 2 + 2 + 1 = 5 ordered binary trees:

(1)      C         (2)      C
        /                 /
       B                 B
      /                   \
     A                     A

(3)      C         (4)      C
          \                 \
           B                 B
          /                   \
         A                     A

(5)      C
        / \
       B   A

6. Verify each tree by reading root-left-right. Each gives C,B,A. The exhaustive subtree-size split proves that no additional ordered binary-tree shape can qualify. In explicit node(left,right) notation, with - for no child, the five trees are C(B(A(-,-),-),-), C(B(-,A(-,-)),-), C(-,B(A(-,-),-)), C(-,B(-,A(-,-))), and C(B(-,-),A(-,-)).

Original paper, page 7

1 mark · MCQ
Report issue

Parent index in a one-based binary heap

Heaps & Priority Queues

Question 1.15, GATE 2001: A binary heap occupies array indices 1 through n. For an element at index i, choose the parent index from i−1, floor(i/2), ceil(i/2), and (i+1)/2. Account for the root boundary.
Tap to enlarge
Your answer
Answer & solution

Answer: B for nonroot nodes (no official key was published)

Step 1: A node at index j has left child 2j and right child 2j+1. For an even child index i=2j, division gives i/2=j. For an odd child i=2j+1, floor(i/2)=j.

Step 2: Both cases are captured by floor(i/2), B. For example indices 6 and 7 both have parent 3; ceiling would incorrectly map 7 to 4.

Boundary: The root at i=1 has no parent. The formula returns sentinel index 0, outside the heap, rather than describing a genuine parent.

Original paper, page 2

2 marks · MCQ
Report issue

Implementing a queue with stacks

Stacks & Queues

Question 2.16, GATE 2001: Under the usual stack-only auxiliary-storage model, what is the minimum number of size-n stacks needed to implement a size-n queue: one, two, three, or four?
Tap to enlarge
Your answer
Answer & solution

Answer: B under the standard auxiliary-storage model (no official key was published)

Step 1: Push new elements onto an input stack. To dequeue, pop from an output stack; when that stack is empty, move all input elements to it. The reversal places the oldest element on top, so two stacks suffice.

Step 2: With only one LIFO stack and O(1) other element storage, reaching the oldest of n elements requires removing and retaining n−1 newer elements somewhere, so the usual general implementation needs the second stack.

Hence B in this model. A recursive “one explicit stack” implementation uses the call stack as another unbounded stack; allowing an auxiliary array or such hidden storage changes what is being counted.

Original paper, page 6

Descriptive
Report issue

Build a binary search tree

Binary Search & Balanced Trees

Question 14(a), GATE 2001: Insert 15,32,20,9,3,25,12,1 into an initially empty BST.
Question 14(a), GATE 2001: Insert 15,32,20,9,3,25,12,1 into an initially empty BST.
Tap to enlarge
Answer & solution

Answer: Root 15; left subtree 9(3(1,∅),12); right subtree 32(20(∅,25),∅). (no official key was published)

Step through it (19 steps)

Use the rule smaller keys go left and larger keys go right. Insert 15 as root; 32 right of 15; 20 left of 32; 9 left of 15; 3 left of 9; 25 right of 20; 12 right of 9; 1 left of 3.

        15
       /  \
      9    32
     / \   /
    3  12 20
   /       \
  1        25

Accessible description: root 15 has children 9 and 32. Node 9 has children 3 and 12; node 3 has left child 1. Node 32 has left child 20, whose right child is 25. All other links are null. Inorder traversal 1,3,9,12,15,20,25,32 verifies the ordering.

Original paper, page 9

Descriptive
Report issue

Delete the BST root

Binary Search & Balanced Trees

Question 14(b), GATE 2001: Delete key 15 from the BST built by insertion order 15,32,20,9,3,25,12,1.
Question 14(b), GATE 2001: Delete key 15 from the BST built by insertion order 15,32,20,9,3,25,12,1.
Question 14(b), GATE 2001: Delete key 15 from the BST built by insertion order 15,32,20,9,3,25,12,1.
Tap to enlarge
Answer & solution

Answer: Successor replacement yields root 20; predecessor replacement yields root 12. (no official key was published)

Choose inorder-successor replacement: the least key in the right subtree of 15 is 20. Copy 20 into the root and remove the old 20 node, reconnecting its right child 25 as the left child of 32.

        20
       /  \
      9    32
     / \   /
    3  12 25
   /
  1

Accessible description: root 20 has children 9 and 32; 9 has children 3 and 12; 3 has left child 1; 32 has left child 25. Alternatively, inorder-predecessor replacement uses 12 as root and removes the old leaf 12. That result is 12(9(3(1,∅),∅),32(20(∅,25),∅)). Both are valid because the question does not prescribe which replacement policy to use.

Original paper, page 9

Descriptive
Report issue

Complete recursive tree depth

Tree Properties & Traversals

Question 14(c), GATE 2001: depth(t) returns 0 for NULL, sets x=depth(t->left), then needs S1, S2 and S3 to return the tree depth.
Question 14(c), GATE 2001: depth(t) returns 0 for NULL, sets x=depth(t->left), then needs S1, S2 and S3 to return the tree depth.
Tap to enlarge
Answer & solution

Answer: S1: y=depth(t->right); S2: x+1; S3: y+1. (no official key was published)

The null-tree base case fixes depth as the number of nodes on a longest root-to-leaf path. Each nonempty tree contributes its root plus the larger child depth. Full compilable function:

#include <stddef.h>
typedef struct node {
    int key;
    struct node *left, *right;
} *Tree;
int depth(Tree t) {
    int x, y;
    if (t == NULL) return 0;
    x = depth(t->left);
    y = depth(t->right); /* S1 */
    if (x > y) return x + 1; /* S2 */
    else return y + 1; /* S3 */
}

A leaf returns 1. The preceding tree returns 4. Each node is visited once, giving O(n) time and O(h) recursive stack space; an edge-count definition would require a different base case and is not the convention of the supplied program.

Original paper, page 9

Descriptive
Report issue

Construct the B+ tree

B-Trees & Multiway Search Trees

Question 22(a), GATE 2001: B+ tree fan-out 3; insert 80,50,10,70,30,100,90, and show snapshots after 10,30,90.
Question 22(a), GATE 2001: B+ tree fan-out 3; insert 80,50,10,70,30,100,90, and show snapshots after 10,30,90.
Tap to enlarge
Answer & solution

Answer: With left-heavy leaf splits: after 10 root[80]; after 30 root[70]; after 90 root[70] with internal children[50] and[80,100]. (no official key was published)

B+ tree fan-out 3, initially empty; insert 80,50,10,70,30,100,90. Use at most 3 child pointers (2 separators) per internal node and at most 2 records per leaf. Non-root internal nodes need ≥2 children; non-root leaves need ≥1 record. Policy: split an overflowing 3-record leaf as 2 records on the left and 1 on the right; copy the minimum key of the right leaf upward. Split an overflowing internal node with 4 children into two groups of 2 children, promoting the middle separator. Internal separators equal the minimum key of their right subtree. Leaf links run left-to-right.

After inserting 10:
        [80]
       /    \
 [10,50] -> [80]

Insert 70: leaves become [10,50],[70],[80], root [70,80]. Inserting 30 splits the first leaf into [10,30] and [50], overflows the root to four children, and creates a new root:

            [70]
          /      \
       [50]      [80]
      /   \     /   \
 [10,30] [50] [70] [80]

Insert 100 into the last leaf. Insert 90 there, split [80,90,100] into [80,90] and [100], and add separator 100 to its parent. Final tree after 90:

             [70]
          /        \
       [50]       [80,100]
      /   \      /   |    \
 [10,30] [50]  [70] [80,90] [100]

Accessible description: root separator 70; left internal separator 50 points to leaves [10,30] and [50]; right internal separators 80,100 point to [70],[80,90],[100]. All leaves have equal depth and are linked in the displayed order. Other consistently applied split policies can yield different valid trees; this is one fully specified construction.

Original paper, page 10

Descriptive
Report issue

Delete from the B+ tree

B-Trees & Multiway Search Trees

Question 22(b), GATE 2001: B+ tree fan-out 3, initially empty; insert 80,50,10,70,30,100,90. Use at most 3 child pointers (2 separators) per internal node and at most 2 records per leaf. Non-root internal nodes need ≥2 children; non-root leaves need ≥1 record. Starting with the final tree of the preceding solution, delete 30 and then 10.
Question 22(b), GATE 2001: B+ tree fan-out 3, initially empty; insert 80,50,10,70,30,100,90. Use at most 3 child pointers (2 separators) per internal node and at most 2 records per leaf. Non-root internal nodes need ≥2 children; non-root leaves need ≥1 record. Starting with the final tree of the preceding solution, delete 30 and then 10.
Question 22(b), GATE 2001: B+ tree fan-out 3, initially empty; insert 80,50,10,70,30,100,90. Use at most 3 child pointers (2 separators) per internal node and at most 2 records per leaf. Non-root internal nodes need ≥2 children; non-root leaves need ≥1 record. Starting with the final tree of the preceding solution, delete 30 and then 10.
Tap to enlarge
Answer & solution

Answer: After 30: leaf [10,30] becomes [10]. After 10: root [80], left internal[70] with [50],[70], right internal[100] with [80,90],[100]. (no official key was published)

Use the exact insertion policy and final tree in part (a). Deletion policy: remove a record, repair an empty leaf by borrowing from an adjacent same-parent sibling if it has spare records; otherwise merge. Repair an underfull internal node by borrowing one child from an adjacent same-parent sibling with spare children; otherwise merge. Update separators to right-subtree minima throughout.

After deleting 30, [10,30] becomes [10]. One record meets the minimum, so no redistribution occurs:

             [70]
          /        \
       [50]       [80,100]
      /   \      /   |    \
   [10] [50]    [70] [80,90] [100]

After deleting 10, the leftmost leaf is empty. Its sibling [50] cannot lend because it has the minimum one record. Merge into [50], remove the obsolete separator 50, and the left internal node temporarily has only one child. Its right internal sibling has three children and can lend its first child [70]. Move that child to the left internal node; update the root separator from 70 to 80. The final tree is:

             [80]
          /        \
       [70]        [100]
      /   \       /    \
   [50]  [70]  [80,90] [100]

Accessible description: root 80 has left internal node 70 with leaf children [50],[70], and right internal node 100 with leaf children [80,90],[100]. The linked leaf sequence is [50]→[70]→[80,90]→[100]. All capacity, occupancy, ordering and equal-depth invariants hold. A different valid policy in part (a) needs its own consistent deletion trace.

Original paper, page 10

1 mark · MCQ
Report issue

Algorithm and data-structure matching

Stacks & Queues

Question 1.13, GATE 2000: Match X depth-first search,Y breadth-first search,Z sorting to 1 heap,2 queue,3 stack.
Question 1.13, GATE 2000: Match X depth-first search,Y breadth-first search,Z sorting to 1 heap,2 queue,3 stack.
Tap to enlarge
Your answer
Answer & solution

Answer: C: X3,Y2,Z1 (no official key was published)

Step 1: DFS must return to the latest unfinished branch, a last-in-first-out behavior implemented by an explicit stack or recursive call stack. Thus X→3.

Step 2: BFS processes older discovered vertices first, using a FIFO queue, so Y→2. A heap supports repeated minimum/maximum extraction for sorting, so Z→1.

Together these matches give C. The sorting match refers to heap sort, not to every possible sorting algorithm.

Original paper, page 2

1 mark · MCQ
Report issue

Well-formed nested binary-tree notation

Tree Properties & Traversals

Question 1.14, GATE 2000: A nonleaf is written (root left right), with leaves represented by labels and empty subtrees by NULL. Choose a valid expression: A (1 2 (4 5 6 7)); B (1 ((2 3 4) 5 6) 7); C (1 (2 3 4) (5 6 7)); D (1 (2 3 NULL) (4 5)).
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Step 1: Every parenthesized node must begin with a node label and have exactly two child descriptions. C has root 1, left subtree rooted 2 with leaves 3,4, and right subtree rooted 5 with leaves 6,7.

Step 2: A gives node 4 three children. B uses a whole subtree where a root label should be. D gives node 4 only one child without an explicit second subtree.

Only C consistently follows the notation.

Original paper, page 2

2 marks · MCQ
Report issue

Last visited vertices in binary-tree traversals

Tree Properties & Traversals

Question 2.16, GATE 2000: For a “complete binary tree,” compare the last vertices in postorder,inorder,preorder. Options equate inorder/postorder,inorder/preorder,preorder/postorder,or none.
Tap to enlarge
Your answer
Answer & solution

Answer: D for heap-complete trees; B for perfect/full-rightmost-path convention (no official key was published)

Step 1: Postorder ends at the root. Inorder ends at the rightmost node, while preorder ends at the last leaf visited after exploring subtrees.

Step 2: Under the modern complete-tree definition (last level filled left to right), take six heap-indexed nodes. Node 3 has left child 6 but no right child. Inorder ends at 3, preorder at 6, and postorder at 1. All three differ, so none of the proposed equalities is always true: D.

If “complete” is intended to mean perfect, the rightmost node is a leaf and is last in both inorder and preorder, giving B. The terminology ambiguity is retained rather than silently imposing the stronger shape.

Original paper, page 5

Descriptive
Report issue

Implement queue with reversible stack

Stacks & Queues

Question 13(a), GATE 2000: A stack supports PUSH, POP and REVERSE, which reverses all its elements. Implement ENQUEUE with one operation and DEQUEUE with three.
Question 13(a), GATE 2000: A stack supports PUSH, POP and REVERSE, which reverses all its elements. Implement ENQUEUE with one operation and DEQUEUE with three.
Tap to enlarge
Answer & solution

Answer: ENQUEUE(x): PUSH(x). DEQUEUE: REVERSE; x = POP(); REVERSE; return x. (no official key was published)

Maintain the queue front at the bottom of the stack and its rear at the top. If queue order is a,b,c (a oldest), the stack bottom-to-top is [a,b,c]. ENQUEUE(d) executes PUSH(d), producing [a,b,c,d], exactly the required FIFO order. To remove the oldest element, REVERSE changes the stack to [d,c,b,a], POP returns a, and the second REVERSE restores [b,c,d]. Thus the invariant is restored after each completed operation. The return statement is not an additional stack operation. On an empty queue, detect underflow rather than POP an absent item. The question counts interface operations, not their implementation costs: REVERSE may require linear time in an ordinary stack representation.

Original paper, page 8

Report issue

Trace first postfix prefix

Stacks & Queues

Question 13(b)(i), GATE 2000: Evaluate the postfix expression 5 2 * 3 4 + 5 2 * * + with single-digit operands, binary addition and multiplication. Stacks below are bottom-to-top. Give the stack after prefix 5 2 * 3 4 +.
Question 13(b)(i), GATE 2000: Evaluate the postfix expression 5 2 * 3 4 + 5 2 * * + with single-digit operands, binary addition and multiplication. Stacks below are bottom-to-top. Give the stack after prefix 5 2 * 3 4 +.
Question 13(b)(i), GATE 2000: Evaluate the postfix expression 5 2 * 3 4 + 5 2 * * + with single-digit operands, binary addition and multiplication. Stacks below are bottom-to-top. Give the stack after prefix 5 2 * 3 4 +.
Tap to enlarge
Answer & solution

Answer: [10, 7], top = 7 (no official key was published)

Step through it (7 steps)

Read left to right. An operand is pushed; an operator pops the right operand first and then the left, computes left operator right, and pushes the result. The successive stacks are [5], [5,2], [10], [10,3], [10,3,4], [10,7]. The multiplication consumes 5 and 2 to produce 10; the addition consumes only 3 and 4 to produce 7. The earlier 10 remains below the new result. Therefore the requested stack is bottom [10,7] top.

Original paper, page 8

Report issue

Trace second postfix prefix

Stacks & Queues

Question 13(b)(ii), GATE 2000: Evaluate the postfix expression 5 2 * 3 4 + 5 2 * * + with single-digit operands, binary addition and multiplication. Stacks below are bottom-to-top. Give the stack after prefix 5 2 * 3 4 + 5 2.
Question 13(b)(ii), GATE 2000: Evaluate the postfix expression 5 2 * 3 4 + 5 2 * * + with single-digit operands, binary addition and multiplication. Stacks below are bottom-to-top. Give the stack after prefix 5 2 * 3 4 + 5 2.
Question 13(b)(ii), GATE 2000: Evaluate the postfix expression 5 2 * 3 4 + 5 2 * * + with single-digit operands, binary addition and multiplication. Stacks below are bottom-to-top. Give the stack after prefix 5 2 * 3 4 + 5 2.
Tap to enlarge
Answer & solution

Answer: [10, 7, 5, 2], top = 2 (no official key was published)

Step through it (9 steps)

The prefix 5 2 * 3 4 + leaves [10,7]: 5*2=10 and 3+4=7 are two independent partial results. The next token 5 is an operand, so push it to obtain [10,7,5]. Push the next operand 2 to obtain [10,7,5,2]. Stop here: the following multiplication has not yet been read, so 5 and 2 must remain separate entries. The top is 2 and the bottom is 10.

Original paper, page 8

Report issue

Finish postfix evaluation

Stacks & Queues

Question 13(b)(iii), GATE 2000: Evaluate the postfix expression 5 2 * 3 4 + 5 2 * * + with single-digit operands, binary addition and multiplication. Stacks below are bottom-to-top. Give the stack at the end.
Question 13(b)(iii), GATE 2000: Evaluate the postfix expression 5 2 * 3 4 + 5 2 * * + with single-digit operands, binary addition and multiplication. Stacks below are bottom-to-top. Give the stack at the end.
Question 13(b)(iii), GATE 2000: Evaluate the postfix expression 5 2 * 3 4 + 5 2 * * + with single-digit operands, binary addition and multiplication. Stacks below are bottom-to-top. Give the stack at the end.
Tap to enlarge
Answer & solution

Answer: [80] (no official key was published)

Step through it (12 steps)

After 5 2 * 3 4 + 5 2 the stack is [10,7,5,2]. The next * replaces the top two entries 5,2 by 10, leaving [10,7,10]. The following * replaces 7,10 by 70, leaving [10,70]. Finally + replaces 10,70 by 80, leaving [80]. There are six operand tokens and five binary operators, so a valid complete evaluation must leave exactly one entry. In infix form the expression is (5*2)+((3+4)*(5*2))=10+7*10=80.

Original paper, page 8

Descriptive
Report issue

Trace sparse-set initialization

Arrays & Linked Lists

Question 15(a), GATE 2000: Arrays p[1..N] and q[1..N] initially contain arbitrary values; count=0. Pseudocode:
set(i) { count=count+1; q[count]=i; p[i]=count; }
is_set(i) { if (p[i]<=0 or p[i]>count) return false; if (q[p[i]]!=i) return false; return true; }
Assume valid indices and no capacity overflow. GateForum calls set(7); set(3); set(9). Find count, q[1..3], p[7],p[3],p[9].
Question 15(a), GATE 2000: Arrays p[1..N] and q[1..N] initially contain arbitrary values; count=0. Pseudocode:
set(i) { count=count+1; q[count]=i; p[i]=count; }
is_set(i) { if (p[i]<=0 or p[i]>count) return false; if (q[p[i]]!=i) return false; return true; }
Assume valid indices and no capacity overflow. GateForum calls set(7); set(3); set(9). Find count, q[1..3], p[7],p[3],p[9].
Question 15(a), GATE 2000: Arrays p[1..N] and q[1..N] initially contain arbitrary values; count=0. Pseudocode:
set(i) { count=count+1; q[count]=i; p[i]=count; }
is_set(i) { if (p[i]<=0 or p[i]>count) return false; if (q[p[i]]!=i) return false; return true; }
Assume valid indices and no capacity overflow. GateForum calls set(7); set(3); set(9). Find count, q[1..3], p[7],p[3],p[9].
Tap to enlarge
Answer & solution

Answer: count=3; q[1..3]=[7,3,9]; p[7]=1, p[3]=2, p[9]=3. (no official key was published)

Starting from count=0, set(7) increments count to 1, writes q[1]=7 and p[7]=1. Then set(3) increments count to 2, writes q[2]=3 and p[3]=2. Finally set(9) increments count to 3, writes q[3]=9 and p[9]=3. The other initially arbitrary array cells need not be initialized to answer these queries.
If that literal reading is used, the result is count=3, q=[7,8,9], p[7]=1, p[8]=2, p[9]=3, while p[3] remains arbitrary.

Original paper, page 8

Descriptive
Report issue

Identify initialized inverse-array prefix

Arrays & Linked Lists

Question 15(b), GATE 2000: Arrays p[1..N] and q[1..N] initially contain arbitrary values; count=0. Pseudocode:
set(i) { count=count+1; q[count]=i; p[i]=count; }
is_set(i) { if (p[i]<=0 or p[i]>count) return false; if (q[p[i]]!=i) return false; return true; }
Assume valid indices and no capacity overflow. Fill: The first count elements of ____ contain values i such that set(____) has been called.
Question 15(b), GATE 2000: Arrays p[1..N] and q[1..N] initially contain arbitrary values; count=0. Pseudocode:
set(i) { count=count+1; q[count]=i; p[i]=count; }
is_set(i) { if (p[i]<=0 or p[i]>count) return false; if (q[p[i]]!=i) return false; return true; }
Assume valid indices and no capacity overflow. Fill: The first count elements of ____ contain values i such that set(____) has been called.
Question 15(b), GATE 2000: Arrays p[1..N] and q[1..N] initially contain arbitrary values; count=0. Pseudocode:
set(i) { count=count+1; q[count]=i; p[i]=count; }
is_set(i) { if (p[i]<=0 or p[i]>count) return false; if (q[p[i]]!=i) return false; return true; }
Assume valid indices and no capacity overflow. Fill: The first count elements of ____ contain values i such that set(____) has been called.
Tap to enlarge
Answer & solution

Answer: q; i (no official key was published)

The completed sentence is: The first count elements of q contain values i such that set(i) has been called. Each invocation appends its argument to q at the new count and records that position in p. Hence q[1..count] is a dense log of calls, in invocation order. It contains no uninitialized holes because count starts at zero and increases by exactly one before each write. Repeated set(i) calls may put repeated copies of i into q, while p[i] records the latest position. The claim is about values that have been set, not necessarily distinct values.

Original paper, page 8

Descriptive
Report issue

Prove sparse-set rejection

Arrays & Linked Lists

Question 15(c), GATE 2000: Arrays p[1..N] and q[1..N] initially contain arbitrary values; count=0. Pseudocode:
set(i) { count=count+1; q[count]=i; p[i]=count; }
is_set(i) { if (p[i]<=0 or p[i]>count) return false; if (q[p[i]]!=i) return false; return true; }
Assume valid indices and no capacity overflow. Prove is_set(i) returns false if set(i) has never been called, regardless of the initial p[i].
Question 15(c), GATE 2000: Arrays p[1..N] and q[1..N] initially contain arbitrary values; count=0. Pseudocode:
set(i) { count=count+1; q[count]=i; p[i]=count; }
is_set(i) { if (p[i]<=0 or p[i]>count) return false; if (q[p[i]]!=i) return false; return true; }
Assume valid indices and no capacity overflow. Prove is_set(i) returns false if set(i) has never been called, regardless of the initial p[i].
Question 15(c), GATE 2000: Arrays p[1..N] and q[1..N] initially contain arbitrary values; count=0. Pseudocode:
set(i) { count=count+1; q[count]=i; p[i]=count; }
is_set(i) { if (p[i]<=0 or p[i]>count) return false; if (q[p[i]]!=i) return false; return true; }
Assume valid indices and no capacity overflow. Prove is_set(i) returns false if set(i) has never been called, regardless of the initial p[i].
Tap to enlarge
Answer & solution

Answer: Either p[i] is out of the initialized range, or q[p[i]] differs from i. (no official key was published)

There are two exhaustive cases. First, p[i]<=0 or p[i]>count: the first guard returns false before q is indexed, so an arbitrary invalid p[i] cannot cause an out-of-range read. Second, 1<=p[i]<=count: every cell in q[1..count] was explicitly written by some set(j) call and stores that call’s j. Since set(i) never occurred, none of these cells equals i. In particular q[p[i]]!=i, so the second guard returns false. This argument also covers count=0, when every possible integer p[i] fails the range guard. The reverse-pointer check is what prevents a coincidentally plausible initial p[i] from producing a false positive. This is an abstract-array algorithm, not permission to read indeterminate C objects: a literal C implementation must use a representation for which such reads are defined. Calls must stay within the arrays’ capacity; otherwise the premise that q[1..count] is valid fails.

Original paper, page 8

2 marks · Descriptive
Report issue

Constant-time insertion using payload exchange

Arrays & Linked Lists

Question 11(b), GATE 1999: Write a constant-time algorithm to insert data D just before a node whose address p is given in a singly linked list. State any limitation of the method.
Question 11(b), GATE 1999: Write a constant-time algorithm to insert data D just before a node whose address p is given in a singly linked list. State any limitation of the method.
Tap to enlarge
Shared context

Write a constant-time algorithm to insert data D just before a node whose address p is given in a singly linked list. State any limitation of the method.

Answer & solution

Answer: Copy p’s old payload into a new successor, then store D at p; this inserts the value in sequence but changes node identity. (no official key was published)

With only p and no predecessor, one cannot in general redirect the predecessor’s next pointer in constant time while preserving the identity and payload of the existing node p. The standard answer implements insertion in the logical sequence by moving p’s old payload one node forward:

insert_before_value(p, D):
    require p != NULL
    q := allocate_node()        // assumed O(1); handle allocation failure
    q.data := p.data
    q.next := p.next
    p.data := D
    p.next := q
    return p                  // address now containing the inserted value
Before: ... → p:[old] → successor
After:  ... → p:[D]   → q:[old] → successor

The prefix still points to p, so no predecessor lookup is needed. The old data and suffix order are preserved. The method also works when p is the head or the tail. If an external tail pointer is maintained and p was the tail, update tail:=q.

The number of pointer and fixed-size data operations is constant. This assumes payload copying and allocation are constant-time. It does not preserve the old element’s address: external references to p now observe D. If “before the node p” literally requires the same p to remain the old node, the requested operation is impossible from p alone in a general singly linked list; supply its predecessor, an incoming-link pointer, or search from the head in O(n).

Original paper, page 7

3 marks · Descriptive
Report issue

Leaves equal full nodes plus one

Tree Properties & Traversals

Question 12(a), GATE 1999: In a nonempty binary tree, a full node has exactly two children. Prove by induction on height that the number of leaves equals the number of full nodes plus one.
Question 12(a), GATE 1999: In a nonempty binary tree, a full node has exactly two children. Prove by induction on height that the number of leaves equals the number of full nodes plus one.
Tap to enlarge
Shared context

In a nonempty binary tree, a full node has exactly two children. Prove by induction on height that the number of leaves equals the number of full nodes plus one.

Answer & solution

Answer: For every nonempty binary tree, L=F+1, including trees with one-child nodes. (no official key was published)

Use strong induction on the height h, taking a leaf to have height zero. Let L(T) and F(T) count leaves and full nodes in T.

Base h=0: T is a single leaf, so L=1 and F=0, giving L=F+1.

Induction hypothesis: the identity holds for every nonempty binary tree of height less than h. Consider a tree T of height h>0. Its root has one or two children.

If it has one child, the unique child subtree T₁ has smaller height. The root is neither full nor a leaf, so L(T)=L(T₁) and F(T)=F(T₁). By induction L(T)=F(T₁)+1=F(T)+1.

If it has two children with subtrees T₁,T₂, both have smaller height. Here L(T)=L(T₁)+L(T₂) and F(T)=1+F(T₁)+F(T₂), because the root itself is full. Substituting the two induction hypotheses gives L(T)=F(T₁)+1+F(T₂)+1=F(T)+1.

These cases exhaust all roots, proving the claim. The qualification “nonempty” matters: an empty tree has zero leaves and zero full nodes, so the formula would not hold there. It is unnecessary to assume every internal node is full.

Original paper, page 7

2 marks · Descriptive
Report issue

Min-heap insertion and root deletion

Heaps & Priority Queues

Question 12(b), GATE 1999: Insert the specified sequence into an initially empty min-heap and draw the final heap and its state after deleting the root. Source discrepancy: GateForum p11 gives 7,6,5,4,3,2,1; GFG p7 visibly gives 7,6,5,4,2,3,1. Both are solved separately below; no official original is available to adjudicate.
Question 12(b), GATE 1999: Insert the specified sequence into an initially empty min-heap and draw the final heap and its state after deleting the root. Source discrepancy: GateForum p11 gives 7,6,5,4,3,2,1; GFG p7 visibly gives 7,6,5,4,2,3,1. Both are solved separately below; no official original is available to adjudicate.
Tap to enlarge
Shared context

Insert the specified sequence into an initially empty min-heap and draw the final heap and its state after deleting the root. Both are solved separately below; no official original is available to adjudicate.

Answer & solution

Answer: [1,4,2,7,5,6,3] → [2,4,3,7,5,6] (no official key was published)

A binary min-heap has complete-tree shape and each parent no larger than either child. Store it in level order. On insertion append at the next free position and swap upward while smaller than its parent. Do not sort the whole array: a heap is only partially ordered.

[7]
[6, 7]
[5, 7, 6]
[4, 5, 6, 7]
[3, 4, 6, 7, 5]
[2, 4, 3, 7, 5, 6]
[1, 4, 2, 7, 5, 6, 3]

The resulting tree is:
             1
          /     \
         4       2
        / \     / \
       7   5   6   3

Delete the root by moving the final element 3 into its position and removing that final slot. This gives [3,4,2,7,5,6]. Swap 3 with its smaller child 2, giving [2,4,3,7,5,6]. Now 3≤6, so downward repair stops. The final tree is:

             2
          /     \
         4       3
        / \     /
       7   5   6

The paper instead orders the last three insertions as 2,3,1. Its successive arrays are:
[7]
[6, 7]
[5, 7, 6]
[4, 5, 6, 7]
[2, 4, 6, 7, 5]
[2, 4, 3, 7, 5, 6]
[1, 4, 2, 7, 5, 6, 3]

Its root-deletion result therefore also coincides. Preserving both source sequences is still important: agreement of the final answer does not establish that the printed questions were identical.

Original paper, page 7

5 marks · Descriptive
Report issue

Bound records stored at B-tree leaves

B-Trees & Multiway Search Trees

Question 21, GATE 1999: In a B-tree, every non-root internal node has between m and 2m−1 children inclusive. The root is at level 0; all leaves are at level h≥1. Derive minimum and maximum numbers of records in the leaf nodes.
Tap to enlarge
Answer & solution

Answer: Under standard B-tree key occupancy: minimum 2m^(h−1)(m−1); maximum (2m−1)^h(2m−2). (no official key was published)

State the usual B-tree assumptions explicitly: m≥2, an internal node with c children has c−1 records, the non-leaf root has 2 through 2m−1 children, and non-root leaves carry between m−1 and 2m−2 records. The printed child bound alone does not independently specify leaf capacity; these are the conventional B-tree occupancy rules, not B+ tree rules or the alternative maximum-2m convention.
For the minimum, choose two root children and m children at every internal level below the root. The number of leaves is then Lmin=2mh−1: for h=1 there are two leaves; each further level multiplies their count by m. Filling each leaf with m−1 records gives Rmin=2mh−1(m−1).
For the maximum, root and all other internal nodes have 2m−1 children, so Lmax=(2m−1)h. Filling every leaf with 2m−2 records gives Rmax=(2m−1)h(2m−2). Both bounds are attained by uniformly minimally or maximally occupied levels.
These counts exclude records in internal nodes. For example m=2,h=1 gives 2 to 6 leaf records (2 leaves×1 up to 3 leaves×2), not the 3 to 8 total records including the root. If only the literal internal-child bound is permitted without standard leaf-occupancy rules, leaf record counts are underdetermined; only the leaf-node bounds follow with the usual root rule.

Original paper, page 9

1 mark · MCQ
Report issue

Tree facts and traversal uniqueness

Tree Properties & Traversals

Question 1.24, GATE 1998: Which is false: n-node trees have n−1 edges; preorder plus postorder uniquely determine a labelled binary tree; full binary trees have leaves=internal+1; maximum nodes at edge-height h is 2^(h+1)−1?
Tap to enlarge
Your answer
Answer & solution

Answer: B under the full-tree interpretation of complete (no official key was published)

Take a root r with only one child c. Making c the left child or the right child gives the same preorder r, c and postorder c, r, so uniqueness fails: B. A connected acyclic n-node graph has n−1 edges. A full binary tree satisfies 2I=I+L−1, hence L=I+1. Summing complete levels 0 through h gives 2h+1−1. The source says “complete” for the leaf formula; modern heap-complete trees may have a one-child node, invalidating that formula. Under that terminology C can fail too, so the intended full/proper definition is a qualification.

Original paper, page 3

2 marks · MCQ
Report issue

Row-major array address

Arrays & Linked Lists

Question 2.14, GATE 1998: A[1…10][1…15] is stored in row-major order, uses one memory location per integer, and A[1][1] is at 100. Find address A[i][j].
Tap to enlarge
Your answer
Answer & solution

Answer: A: 15i+j+84 (no official key was published)

Before row i there are i−1 complete rows, each containing 15 entries, contributing 15(i−1) locations. Within row i, column j is j−1 locations beyond its start. Add the base:100+15(i−1)+(j−1)=15i+j+84. This is A. Check i=j=1 gives 100, and increasing j by 1 advances one location, whereas increasing i by 1 advances fifteen. Those checks distinguish row-major from column-major formulas.

Original paper, page 5

Descriptive
Report issue

Linked-list pointer manipulation

Arrays & Linked Lists

Question 19(a), GATE 1998: Initially p points to node i in i→i+1→i+2→i+3→suffix. Execute q=p.next; p.next=q.next; q.next=(q.next).next; (p.next).next=q. GateForum instead prints p.next, not q.next, on the third line. Explain both.
Question 19(a), GATE 1998: Initially p points to node i in i→i+1→i+2→i+3→suffix. Execute q=p.next; p.next=q.next; q.next=(q.next).next; (p.next).next=q. GateForum instead prints p.next, not q.next, on the third line. Explain both.
Tap to enlarge
Answer & solution

Answer: It swaps nodes i+1 and i+2 (no official key was published)

Write P=i, A=i+1, B=i+2 and C=i+3. Initially P→A→B→C→suffix. Third line, step 1 sets q=A. Step 2 bypasses A by setting P.next=B. Step 3 sets A.next=C, preserving the link to the suffix. Step 4 sets B.next=A. The resulting chain is P→B→A→C→suffix: the two adjacent nodes after p have been exchanged without copying their payloads. This requires those nodes and the next fields used in the expressions to exist.

After the first two steps, q=A, P.next=B, A.next=B and B.next=C. Its third line sets P.next=C instead of changing A.next. Its last line then sets C.next=A. Thus from P the chain becomes P→C→A→B→C→..., a three-node cycle; the original suffix after C is detached from this chain. It is not an adjacent swap.

The correct algorithmic explanation cannot establish which version appeared in the official original.

Original paper, page 7

Descriptive
Report issue

Postfix conversion

Stacks & Queues

Question 19(b), GATE 1998: Find postfix for 3*log(x+1)−a/2.
Question 19(b), GATE 1998: Find postfix for 3*log(x+1)−a/2.
Tap to enlarge
Answer & solution

Answer: 3 x 1 + log * a 2 / − (no official key was published)

Step through it (14 steps)

First parenthesize by the usual precedence and the unary function call: (3*log(x+1))−(a/2). A postfix traversal writes operands before their operator. The subtree x+1 becomes x 1 +; applying the unary log appends log, giving x 1 + log. Multiplication by 3 becomes 3 x 1 + log *. Independently, a/2 becomes a 2 /. Finally append subtraction after both subexpressions:

3 x 1 + log * a 2 / −

The spaces separate tokens, and log is one unary operator rather than three operands. Evaluating this stack form pushes 3, forms log(x+1), multiplies, forms a/2, then subtracts the right value from the left. Reversing the final operands would change the expression.

Original paper, page 7

5 marks · Descriptive
Report issue

Reconstruct traversal tree

Tree Properties & Traversals

Question 20, GATE 1998: Construct the tree with inorder a f b c d g e and postorder a f c g e d b.
Question 20, GATE 1998: Construct the tree with inorder a f b c d g e and postorder a f c g e d b.
Tap to enlarge
Answer & solution

Answer: Root b; left f with left a; right d with left c and right e with left g. (no official key was published)

The final postorder symbol b is the root. Split inorder around b: left subtree has a,f and right subtree has c,d,g,e. The corresponding postorder chunks are a,f and c,g,e,d.

For the left subtree, final f is its root and a lies to its left, so f has left child a and no right child. For the right subtree, final d is its root. Inorder splits into c on its left and g,e on its right. The left child is c. The right chunk has postorder g,e, hence root e with left child g.

        b
       / \
      f   d
     /   / \
    a   c   e
           /
          g

Checking inorder yields a,f,b,c,d,g,e. Checking postorder yields a,f,c,g,e,d,b. The labels are distinct, so the recursive splits uniquely determine the tree. A different shape that merely shares the root would not suffice.

Original paper, page 7

Descriptive
Report issue

Minimum AVL recurrence

Binary Search & Balanced Trees

Question 21(a), GATE 1998: Derive the minimum number N(h) of nodes in an AVL tree of height h. State the height convention.
Question 21(a), GATE 1998: Derive the minimum number N(h) of nodes in an AVL tree of height h. State the height convention.
Tap to enlarge
Answer & solution

Answer: N(h)=1+N(h−1)+N(h−2); edge-height bases N(−1)=0,N(0)=1. (no official key was published)

Take height to count edges on a longest root-to-leaf path; an empty tree has height −1 and a leaf height 0. A tree of height h must have at least one child subtree of height h−1. AVL balance permits the other to be no shorter than h−2. To minimize nodes, choose exactly those two heights and make both subtrees themselves minimum-size AVL trees. Counting the root gives N(h)=1+N(h−1)+N(h−2), with N(−1)=0,N(0)=1.

This is both a lower bound and attainable: recursively attach extremal subtrees of heights h−1 and h−2 to a root. The height difference is one, so the construction is AVL. Writing M(h)=N(h)+1 gives M(h)=M(h−1)+M(h−2), and the bases imply N(h)=Fh+3−1 when F0=0,F1=1.

If height instead counts levels, the empty tree is height 0 and a leaf height 1, so the same recurrence has bases N(0)=0,N(1)=1 and formula Fh+2−1. The recurrence is structural; the indexing convention must not be mixed between parts.

Original paper, page 8

Descriptive
Report issue

Minimum AVL height eight

Binary Search & Balanced Trees

Question 21(b), GATE 1998: Find the smallest AVL tree size for height 8.
Question 21(b), GATE 1998: Find the smallest AVL tree size for height 8.
Tap to enlarge
Answer & solution

Answer: 88 nodes for edge height; 54 for level height. (no official key was published)

Using the edge-height convention from part (a), start N(−1)=0,N(0)=1 and apply N(h)=1+N(h−1)+N(h−2). The values at heights 1 through 8 are 2,4,7,12,20,33,54,88. Thus the smallest tree at edge height 8 has 88 nodes. Equivalently, F11−1=89−1=88.

If the source's unstated height convention counts levels, the same physical tree's level height is one larger. A level-height-8 minimum tree therefore has edge height 7 and 54 nodes. This is not a disagreement in AVL structure, only an indexing ambiguity. Specify the convention rather than asserting both numbers describe the same notion of height. The printed empty '(c)' after this question contains no task text and is not invented as another solution item.

Original paper, page 8

1 mark · MCQ
Report issue

Constant-time list concatenation

Arrays & Linked Lists

Question 1.4, GATE 1997: Which standard representation permits O(1) concatenation: singly linked, doubly linked, circular doubly linked, or array list?
Tap to enlarge
Your answer
Answer & solution

Answer: C with head-only representations; stored tails also suffice (no official key was published)

A circular doubly linked list exposes its tail as head.prev. For nonempty lists with heads h1, h2 and tails t1, t2, set t1.next=h2, h2.prev=t1, t2.next=h1, h1.prev=t2. Only four links change, so concatenation is O(1), C. Empty-list cases need only pointer assignments. A head-only linear list requires traversal to find its tail, but an explicitly stored tail pointer also makes singly or doubly linked concatenation constant-time. Thus uniqueness of C depends on the usual representation metadata, not merely the link direction.

Original paper, page 1

1 mark · MCQ
Report issue

Infix-to-postfix conversion storage

Stacks & Queues

Question 1.7, GATE 1997: Which structure is essential for efficient infix-to-postfix conversion: operator stack, operand stack, both stacks, or parse tree?
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Operands can be emitted directly to the postfix output. Operators must wait until higher-precedence operators and parenthesized subexpressions are resolved, so a stack stores pending operators and delimiters. When an operator is popped, it is appended to the output. Thus the standard shunting-yard conversion needs an operator stack, A, not an operand-value stack. An operand stack is used later to evaluate postfix, and an explicit parse tree is an alternative representation rather than a requirement of this direct conversion.

Original paper, page 1

2 marks · MCQ
Report issue

Valid BST preorder

Binary Search & Balanced Trees

Question 4.5, GATE 1997: A BST contains 1…8. Which preorder is valid:53124786, 53126487, 53241678, 53124768?
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

For D, root 5 divides the remaining sequence into left subtree 3, 1, 2, 4 and right subtree 7, 6, 8. In the left subtree, 3 has left subtree 1→right child 2 and right child 4. In the right subtree, 7 has children 6 and 8. This constructs the required BST. A gives 7, 8, 6 after entering root 7’s right subtree before returning to a smaller value 6. B returns to 4 after beginning root 5’s right subtree at 6. C returns to 1 after entering the right subtree of 3 at 4. These violate preorder’s contiguous subtree blocks, leaving D.

Original paper, page 4

2 marks · MCQ
Report issue

Implementing a stack with delete-min

Stacks & Queues

Question 4.7, GATE 1997: A priority queue is used to implement a LIFO stack. PUSH inserts an item with a chosen integer key; POP deletes the minimum. Should keys be nonincreasing, nondecreasing, strictly increasing, or strictly decreasing?
Tap to enlarge
Your answer
Answer & solution

Answer: D as the sufficient unambiguous scheme (no official key was published)

The newest live item must have the smallest key so it is returned first. Assign successively decreasing keys, for example 0, −1, −2, …; then delete-min exactly follows last-in-first-out order. Strict decrease prevents ties whose unspecified resolution could return an older item. Thus D is the standard sufficient choice. A merely nonincreasing sequence permits equal keys and does not guarantee LIFO without an extra tie rule. Keys need only outrank still-live items, so global decrease is a simple implementation policy rather than the only possible schedule-aware assignment.

Original paper, page 4

5 marks · Descriptive
Report issue

Swap consecutive linked-list nodes

Arrays & Linked Lists

Question 8, GATE 1997: A singly linked list L=(a1,…,an), n≥0, has nodes with fields next:^list and val:integer. Swap adjacent pairs a_(2i−1),a_(2i), 1≤i≤floor(n/2), by filling the four boxes:
1 function change(p:^list):^list;
2 var q,t:^list;
3 begin
4   if p=nil then change:=p
5   else if p^.next=nil then change:=[B5]
6   else begin
7     q:=p^.next;
8     [B8]:=q;
9     t:=q^.next;
10    [B10]:=p;
11    [B11]:=change(t)
12  end
13 end
Tap to enlarge
Answer & solution

Answer: B5=p; B8=change; B10=q^.next; B11=p^.next. (no official key was published)

The required fillings are line 5: p; line 8: change; line 10: q^.next; line 11: p^.next. With them, the nontrivial branch is

q := p^.next;
change := q;
t := q^.next;
q^.next := p;
p^.next := change(t).

Before the change, the first two nodes and the remaining list have the shape p → q → t. The function must return q as the new head, so line 8 assigns the function result rather than overwriting a next pointer. Save t before reversing q's link; otherwise the remaining list could be lost. Then q^.next:=p reverses the first pair, and p^.next:=change(t) joins its second node to the recursively transformed remainder. The final shape is q → p → change(t).

For an empty list, returning nil preserves it. For a one-node list, returning p preserves the last unpaired node. These are also the induction bases. Assuming the recursive call correctly swaps all pairs in the suffix of length n−2, linking the reversed first pair to that result swaps every required pair in the whole list and preserves every node exactly once.

For example, 1→2→3→4→5 becomes 2→1→4→3→5. The code exchanges nodes through pointers, not merely their stored integer values. It takes Θ(n) time and Θ(n) recursive-stack space, with about floor(n/2) pair-processing calls. Pascal's function-name assignment in line 8 is the mechanism for returning a pointer; it is not another recursive call.

Original paper, page 6

3 marks · Descriptive
Report issue

Bound size-balanced tree size

Binary Search & Balanced Trees

Question 16(a), GATE 1997: A size-balanced binary tree has, at every node, left and right subtree sizes differing by at most one. Node distance is the number of edges from the root, and tree height h is the greatest root-to-leaf distance. Prove by induction on h that a tree of height h has at least 2^h nodes.
Question 16(a), GATE 1997: A size-balanced binary tree has, at every node, left and right subtree sizes differing by at most one. Node distance is the number of edges from the root, and tree height h is the greatest root-to-leaf distance. Prove by induction on h that a tree of height h has at least 2^h nodes.
Tap to enlarge
Answer & solution

Answer: Every such tree has N≥2^h; the bound is attainable. (no official key was published)

Use induction on the nonnegative height h. For h=0 the tree consists of the root, so N=1=20.

For h≥1, at least one child subtree has height h−1; otherwise no root-to-leaf path could have length h. Call that subtree T and let its size be s. By the induction hypothesis, s≥2h−1. The other child subtree has size t≥s−1, because the defining balance condition bounds the size difference by one. Empty subtrees are allowed and have size zero, so this also handles h=1.

Counting the root gives

N=1+s+t ≥1+s+(s−1)=2s ≥2h.

This proves the assertion. We did not assume the two subtrees have equal height or that every level is full. Size balance is a statement about node counts, and the proof uses exactly that statement.

The bound is sharp. For h≥1, combine a minimum-size tree of height h−1, with 2h−1 nodes, and a perfect tree of height h−2, with 2h−1−1 nodes, below a new root. Their sizes differ by one and their subtrees satisfy the same condition. The total is 2h and the height is h. At h=1 the smaller subtree is empty. This construction also explains why the stronger bound 2h+1−1 would be false: a size-balanced tree need not be perfect at its last level.

Original paper, page 8

2 marks · Descriptive
Report issue

Count the penultimate tree level

Binary Search & Balanced Trees

Question 16(b), GATE 1997: A size-balanced binary tree has, at every node, left and right subtree sizes differing by at most one. Node distance is the number of edges from the root, and tree height h is the greatest root-to-leaf distance. For h≥1, how many nodes are at distance h−1 from the root?
Question 16(b), GATE 1997: A size-balanced binary tree has, at every node, left and right subtree sizes differing by at most one. Node distance is the number of edges from the root, and tree height h is the greatest root-to-leaf distance. For h≥1, how many nodes are at distance h−1 from the root?
Tap to enlarge
Answer & solution

Answer: Exactly 2^(h−1). (no official key was published)

The level at distance h−1 is full, so it contains 2h−1 nodes. To justify fullness rather than assume it, first use the proved size bound: a size-balanced tree of height h has N≥2h nodes.

For any node whose subtree has s nodes, its child sizes sum to s−1 and differ by at most one. Hence each child has at least floor((s−1)/2) nodes. Starting from N≥2h, induction on depth shows that every node at depth d≤h−1 has subtree size at least 2h−d−1. Indeed, a parent lower bound 2h−d−1 gives each child at least 2h−d−1−1.

In particular, at every depth d<h−1 this lower bound is at least 3. Such a subtree has both children nonempty. Beginning with one root, the node count therefore doubles at each step until depth h−1, giving exactly 2h−1 nodes there. The last level h may be only partly occupied, so this does not assert that the entire tree is perfect.

For h=1 the requested level is the root itself and the formula gives 1. For h=2 a smallest example has four nodes: its depth-1 level still has both children, while only one node need occur at depth 2. The paper explicitly states h≥1.

Original paper, page 8

1 mark · Descriptive
Report issue

Count duplicate-removal comparisons

Arrays & Linked Lists

Question 18(a), GATE 1997: The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting.
Node *remove_duplicates(Node *head,int *j) {
  Node *t1,*t2;
  *j=0;
  t1=head;
  if(t1!=NULL) t2=t1->next;
  else return head;
  *j=1;
  if(t2==NULL) return head;
  while(t2!=NULL) {
    if(t1->val!=t2->val) {             /* S1 */
      (*j)++; t1->next=t2; t1=t2;      /* S2 */
    }
    t2=t2->next;
  }
  t1->next=NULL;
  return head;
}
How many times is the comparison S1 evaluated?
Question 18(a), GATE 1997: The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting.
Node *remove_duplicates(Node *head,int *j) {
  Node *t1,*t2;
  *j=0;
  t1=head;
  if(t1!=NULL) t2=t1->next;
  else return head;
  *j=1;
  if(t2==NULL) return head;
  while(t2!=NULL) {
    if(t1->val!=t2->val) {             /* S1 */
      (*j)++; t1->next=t2; t1=t2;      /* S2 */
    }
    t2=t2->next;
  }
  t1->next=NULL;
  return head;
}
How many times is the comparison S1 evaluated?
Question 18(a), GATE 1997: The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting.
Node *remove_duplicates(Node *head,int *j) {
  Node *t1,*t2;
  *j=0;
  t1=head;
  if(t1!=NULL) t2=t1->next;
  else return head;
  *j=1;
  if(t2==NULL) return head;
  while(t2!=NULL) {
    if(t1->val!=t2->val) {             /* S1 */
      (*j)++; t1->next=t2; t1=t2;      /* S2 */
    }
    t2=t2->next;
  }
  t1->next=NULL;
  return head;
}
How many times is the comparison S1 evaluated?
Tap to enlarge
Answer & solution

Answer: n−1. (no official key was published)

The first input node is taken as the initial retained node t1. Before the loop, t2 is set to the second input node. The loop then advances t2 exactly once through every remaining original node, stopping at NULL. Since there are n−1 nodes after the first, S1 is evaluated exactly n−1 times.

Rewiring t1->next inside S2 does not skip any as-yet unvisited node. When S2 executes, t1 is moved to the current t2, but that current node's own next pointer has not been changed. The subsequent t2=t2->next therefore advances to its original successor. When S2 does not execute, t1 remains the retained node and the same successor step still happens. Thus all-equal and all-distinct lists perform the same number of value comparisons.

For example, on [1,1,2,2], S1 compares the second 1, first 2, and second 2 against the current retained value, for three comparisons. The while-condition test is a different comparison and is not included in this count.

This leaf uses the full shared stem and belongs to that single group; it is not evidence for an extra exam question. The displayed code restores legal pointer-member notation while retaining its algorithmic operations.

Original paper, page 9

2 marks · Descriptive
Report issue

Bound duplicate-removal updates

Arrays & Linked Lists

Question 18(b), GATE 1997: The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting.
Node *remove_duplicates(Node *head,int *j) {
  Node *t1,*t2;
  *j=0;
  t1=head;
  if(t1!=NULL) t2=t1->next;
  else return head;
  *j=1;
  if(t2==NULL) return head;
  while(t2!=NULL) {
    if(t1->val!=t2->val) {             /* S1 */
      (*j)++; t1->next=t2; t1=t2;      /* S2 */
    }
    t2=t2->next;
  }
  t1->next=NULL;
  return head;
}
What are the minimum and maximum numbers of executions of the block S2?
Question 18(b), GATE 1997: The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting.
Node *remove_duplicates(Node *head,int *j) {
  Node *t1,*t2;
  *j=0;
  t1=head;
  if(t1!=NULL) t2=t1->next;
  else return head;
  *j=1;
  if(t2==NULL) return head;
  while(t2!=NULL) {
    if(t1->val!=t2->val) {             /* S1 */
      (*j)++; t1->next=t2; t1=t2;      /* S2 */
    }
    t2=t2->next;
  }
  t1->next=NULL;
  return head;
}
What are the minimum and maximum numbers of executions of the block S2?
Question 18(b), GATE 1997: The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting.
Node *remove_duplicates(Node *head,int *j) {
  Node *t1,*t2;
  *j=0;
  t1=head;
  if(t1!=NULL) t2=t1->next;
  else return head;
  *j=1;
  if(t2==NULL) return head;
  while(t2!=NULL) {
    if(t1->val!=t2->val) {             /* S1 */
      (*j)++; t1->next=t2; t1=t2;      /* S2 */
    }
    t2=t2->next;
  }
  t1->next=NULL;
  return head;
}
What are the minimum and maximum numbers of executions of the block S2?
Tap to enlarge
Answer & solution

Answer: Minimum 0; maximum n−1. For d distinct values, the block runs d−1 times. (no official key was published)

The list is sorted, so equal values occur in contiguous runs. The first run's first node is retained before the loop begins. Thereafter S2 executes precisely when t2 reaches the first node of a new value run, because its value differs from that in the last retained node t1.

If the input has d distinct values, there are d runs and exactly d−1 transitions to new runs. Thus the S2 block, and each of its three statements, executes d−1 times. Since 1≤d≤n for a nonempty list, the minimum is 0 and the maximum is n−1.

The minimum occurs when all n values are equal: every comparison S1 is false, t1 stays at the first node, and the final t1->next=NULL detaches all duplicate nodes from the returned chain. The maximum occurs when all n values are distinct: every one of the n−1 loop iterations takes S2, retains the current node and advances t1.

For [1,1,2,2,3], d=3 and S2 runs twice, once on the first 2 and once on the first 3. It does not run once per duplicate removed. This distinction prevents reversing the extremes: an all-equal list removes the most duplicate links but executes S2 the fewest times. The final NULL assignment is outside S2 and is not counted as one of these block executions.

Original paper, page 9

2 marks · Descriptive
Report issue

Interpret the duplicate counter

Arrays & Linked Lists

Question 18(c), GATE 1997: The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting.
Node *remove_duplicates(Node *head,int *j) {
  Node *t1,*t2;
  *j=0;
  t1=head;
  if(t1!=NULL) t2=t1->next;
  else return head;
  *j=1;
  if(t2==NULL) return head;
  while(t2!=NULL) {
    if(t1->val!=t2->val) {             /* S1 */
      (*j)++; t1->next=t2; t1=t2;      /* S2 */
    }
    t2=t2->next;
  }
  t1->next=NULL;
  return head;
}
What does the integer *j contain when the function completes?
Question 18(c), GATE 1997: The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting.
Node *remove_duplicates(Node *head,int *j) {
  Node *t1,*t2;
  *j=0;
  t1=head;
  if(t1!=NULL) t2=t1->next;
  else return head;
  *j=1;
  if(t2==NULL) return head;
  while(t2!=NULL) {
    if(t1->val!=t2->val) {             /* S1 */
      (*j)++; t1->next=t2; t1=t2;      /* S2 */
    }
    t2=t2->next;
  }
  t1->next=NULL;
  return head;
}
What does the integer *j contain when the function completes?
Question 18(c), GATE 1997: The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting.
Node *remove_duplicates(Node *head,int *j) {
  Node *t1,*t2;
  *j=0;
  t1=head;
  if(t1!=NULL) t2=t1->next;
  else return head;
  *j=1;
  if(t2==NULL) return head;
  while(t2!=NULL) {
    if(t1->val!=t2->val) {             /* S1 */
      (*j)++; t1->next=t2; t1=t2;      /* S2 */
    }
    t2=t2->next;
  }
  t1->next=NULL;
  return head;
}
What does the integer *j contain when the function completes?
Tap to enlarge
Answer & solution

Answer: The number of distinct input values, equal to the number of nodes in the returned deduplicated list. (no official key was published)

For a nonempty list, the code explicitly sets *j=1 before entering the loop. This counts the first retained value. Every later S2 execution marks the first encounter with a new value and increments *j once. Since sorted order puts equal values together, no later run repeats an earlier value.

If there are d distinct input values, S2 executes d−1 times and the final value is 1+(d−1)=d. The returned chain contains exactly one representative of each run, so d is also its number of nodes. For [2,2,5,5,5,9], the initialization counts 2, and the two increments count 5 and 9, giving *j=3. The number of removed duplicate nodes is n−*j, not *j itself.

The early cases are consistent even though this question assumes n≥2. An empty list returns with *j=0; a one-node list returns with *j=1. The *j=1 assignment after the empty-list check is therefore essential to interpreting the result. Omitting it would incorrectly leave the counter at d−1.

The function changes links but does not free detached nodes. Its logical output is deduplicated, but claiming that it releases their memory would go beyond the code. Sortedness is also essential for “distinct values”: on an unsorted list such as [1,2,1], the code would count three runs rather than two globally distinct values. This explanation applies to the ordered-list precondition actually given.

Original paper, page 9

1 mark · MCQ
Report issue

List and queue statements

Stacks & Queues

Question 1.12, GATE 1996: Assess FIFO for stacks, broad linked-list efficiency, circular queues reusing array slots, and LIFO for queues.
Question 1.12, GATE 1996: Assess FIFO for stacks, broad linked-list efficiency, circular queues reusing array slots, and LIFO for queues.
Tap to enlarge
Your answer
Answer & solution

Answer: A under the intended linked-list operation model: statements ii and iii (no official key was published)

A stack is LIFO, not FIFO; a queue is FIFO, not LIFO. In a circular array queue, the rear wraps around to locations freed by dequeues, so statement iii is correct. Linked lists permit constant-time insertion or deletion when the relevant node or predecessor is already known, avoiding array shifts; this motivates statement ii and the intended pair ii,iii. However, the assertion that linked lists are more efficient for almost all basic operations is not a mathematical universal: indexed access and cache-local traversal often favor arrays, and locating a node can require linear time. The operation and representation model must be specified.

Original paper, page 2

1 mark · MCQ
Report issue

Deletion with hash chaining

Hashing

Question 1.13, GATE 1996: Why can separate chaining be preferable to open addressing: better worst-case search, less storage, easier deletion, or another claim?
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

In chaining, keys in a bucket form a separate collection. Once the key and necessary predecessor are found, deletion simply unlinks it without changing the search path for other keys. In open addressing, clearing a slot outright may incorrectly terminate a later probe, so deletion needs tombstones or careful reorganization. Both approaches can have linear worst-case search, and chaining normally incurs pointer or container overhead. The reliable advantage among these claims is therefore easier deletion, C, rather than a universal space or worst-case-time improvement.

Original paper, page 2

1 mark · MCQ
Report issue

AVL ancestors after inserting below g

Binary Search & Balanced Trees

Question 1.14, GATE 1996: In the pictured AVL tree, a has children b,e; b has c,d; c has g; e has f. How many nodes become unbalanced when a new child is attached below g, before rebalancing?
Tap to enlarge
Your answer
Answer & solution

Answer: B: 3 (no official key was published)

The insertion increases the height of the subtree rooted at g by one. That increase propagates through c, b and a. At c, its already taller g side becomes two levels taller than its empty opposite side. The same extra level makes b and then a have height difference two. Node g itself has only one new child, so its balance magnitude is one; e and its descendants are unchanged. Thus c,b,a are the three unbalanced nodes before rotations. Counting after AVL repair would answer a different question.

Original paper, page 2

1 mark · MCQ
Report issue

Postorder of the pictured tree

Tree Properties & Traversals

Question 1.15, GATE 1996: For root a with left subtree b(c(g),d) and right subtree e(f), find the postorder traversal.
Question 1.15, GATE 1996: For root a with left subtree b(c(g),d) and right subtree e(f), find the postorder traversal.
Tap to enlarge
Your answer
Answer & solution

Answer: C: g,c,d,b,f,e,a (no official key was published)

Postorder visits the complete left subtree, then the complete right subtree, then the root. Within b, visit g before its parent c, then d, then b: g,c,d,b. Within e, visit f before e: f,e. Concatenate those two lists and finally append a, yielding g,c,d,b,f,e,a. The exact left-versus-right placement of a sole child does not affect postorder. Visiting a before its subtrees would be preorder, not the requested traversal.

Original paper, page 2

2 marks · MCQ
Report issue

Fewest swaps to make a max-heap

Heaps & Priority Queues

Question 2.11, GATE 1996: For array [89,19,40,17,12,10,2,5,7,11,6,9,70], find the minimum arbitrary pair swaps to obtain a max-heap.
Tap to enlarge
Your answer
Answer & solution

Answer: C: 2 (no official key was published)

Using one-based indices, swap entries 13 and 6, then 6 and 3. The array becomes [89,19,70,17,12,40,2,5,7,11,6,9,10], and every parent is at least as large as its children. For a lower bound, initially 70 at index 13 exceeds parent 10 at index 6. Any one-swap repair must change one of those positions. Moving a sufficiently large value into position 6 either puts 70 below a smaller parent or leaves position 6 larger than its parent 40; moving 70 directly to position 3 leaves 40 at 13 above parent 10. Exhaustive checking of all 78 pairs also finds no one-swap heap. Thus two are necessary and sufficient.

Original paper, page 5

2 marks · MCQ
Report issue

Sizes of root subtrees after BST insertion

Binary Search & Balanced Trees

Question 2.14, GATE 1996: Insert 50,15,62,5,20,58,91,3,8,37,60,24 into an empty BST. Count nodes in the left and right subtrees of the root.
Tap to enlarge
Your answer
Answer & solution

Answer: B: 7 and 4 (no official key was published)

Step through it (14 steps)

The first key 50 remains the root in ordinary unbalanced BST insertion. Every later key below 50 belongs somewhere in its left subtree: 15,5,20,3,8,37,24, totaling seven. Every key above 50 belongs in its right subtree: 62,58,91,60, totaling four. Internal insertion paths affect shape but not which side of the root contains each key. The root itself is excluded from both counts, and 7+4+1=12 checks the total number of inserted keys.

Original paper, page 5

Descriptive
Report issue

Test a binary-search-tree probe sequence

Binary Search & Balanced Trees

Question 4(a), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 61, 52, 14, 17, 40, 43 can occur, and explain. GFG instead prints 11 in place of 17 at the fourth probe.
Question 4(a), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 61, 52, 14, 17, 40, 43 can occur, and explain. GFG instead prints 11 in place of 17 at the fourth probe.
Tap to enlarge
Answer & solution

Answer: Impossible (no official key was published)

A search path obeys every ancestor constraint, not merely the immediately preceding comparison. Maintain an open interval of permissible keys, initially (−∞,+∞). When a probe is below 43, searching right raises the lower bound to that probe. When a probe is above 43, searching left lowers the upper bound.

After 61, every later probe must lie in (−∞,61).
After 52, every later probe must lie in (−∞,52).
After 14, every later probe must lie in (14,52).
After 17, every later probe must lie in (17,52).
After 40, every later probe must lie in (40,52).
The final probe is 43, so the search succeeds.

All probes meet the bounds. A witnessing BST can be built as a chain with these keys, taking the left or right child according to each comparison with 43. Thus the bound test proves existence, rather than just failing to find an error.

With 17 the sequence is valid. With 11 it is invalid, because after visiting 14 the search for 43 must stay in the right subtree of 14, whose keys exceed 14. The 11 variant therefore has the opposite answer.

Original paper, page 7

Descriptive
Report issue

Test a binary-search-tree probe sequence

Binary Search & Balanced Trees

Question 4(b), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 2, 3, 50, 40, 60, 43 can occur, and explain.
Question 4(b), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 2, 3, 50, 40, 60, 43 can occur, and explain.
Tap to enlarge
Answer & solution

Answer: Impossible. (no official key was published)

A search path obeys every ancestor constraint, not merely the immediately preceding comparison. Maintain an open interval of permissible keys, initially (−∞,+∞). When a probe is below 43, searching right raises the lower bound to that probe. When a probe is above 43, searching left lowers the upper bound.

After 2, every later probe must lie in (2,+∞).
After 3, every later probe must lie in (3,+∞).
After 50, every later probe must lie in (3,50).
After 40, every later probe must lie in (40,50).
Probe 60 violates the inherited interval (40,50); the sequence is impossible.

The violated bound comes from an earlier ancestor. A later comparison cannot discard it: every node subsequently visited remains inside that ancestor’s chosen subtree. No choice of unvisited nodes can repair this path.

Original paper, page 7

Descriptive
Report issue

Test a binary-search-tree probe sequence

Binary Search & Balanced Trees

Question 4(c), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 10, 65, 31, 48, 37, 43 can occur, and explain.
Question 4(c), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 10, 65, 31, 48, 37, 43 can occur, and explain.
Tap to enlarge
Answer & solution

Answer: Possible. (no official key was published)

A search path obeys every ancestor constraint, not merely the immediately preceding comparison. Maintain an open interval of permissible keys, initially (−∞,+∞). When a probe is below 43, searching right raises the lower bound to that probe. When a probe is above 43, searching left lowers the upper bound.

After 10, every later probe must lie in (10,+∞).
After 65, every later probe must lie in (10,65).
After 31, every later probe must lie in (31,65).
After 48, every later probe must lie in (31,48).
After 37, every later probe must lie in (37,48).
The final probe is 43, so the search succeeds.

All probes meet the bounds. A witnessing BST can be built as a chain with these keys, taking the left or right child according to each comparison with 43. Thus the bound test proves existence, rather than just failing to find an error.

Original paper, page 7

Descriptive
Report issue

Test a binary-search-tree probe sequence

Binary Search & Balanced Trees

Question 4(d), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 81, 61, 52, 14, 41, 43 can occur, and explain.
Question 4(d), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 81, 61, 52, 14, 41, 43 can occur, and explain.
Tap to enlarge
Answer & solution

Answer: Possible. (no official key was published)

A search path obeys every ancestor constraint, not merely the immediately preceding comparison. Maintain an open interval of permissible keys, initially (−∞,+∞). When a probe is below 43, searching right raises the lower bound to that probe. When a probe is above 43, searching left lowers the upper bound.

After 81, every later probe must lie in (−∞,81).
After 61, every later probe must lie in (−∞,61).
After 52, every later probe must lie in (−∞,52).
After 14, every later probe must lie in (14,52).
After 41, every later probe must lie in (41,52).
The final probe is 43, so the search succeeds.

All probes meet the bounds. A witnessing BST can be built as a chain with these keys, taking the left or right child according to each comparison with 43. Thus the bound test proves existence, rather than just failing to find an error.

Original paper, page 7

Descriptive
Report issue

Test a binary-search-tree probe sequence

Binary Search & Balanced Trees

Question 4(e), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 17, 77, 27, 66, 18, 43 can occur, and explain.
Question 4(e), GATE 1996: A BST is searched for key 43. Determine whether the probe sequence 17, 77, 27, 66, 18, 43 can occur, and explain.
Tap to enlarge
Answer & solution

Answer: Impossible. (no official key was published)

A search path obeys every ancestor constraint, not merely the immediately preceding comparison. Maintain an open interval of permissible keys, initially (−∞,+∞). When a probe is below 43, searching right raises the lower bound to that probe. When a probe is above 43, searching left lowers the upper bound.

After 17, every later probe must lie in (17,+∞).
After 77, every later probe must lie in (17,77).
After 27, every later probe must lie in (27,77).
After 66, every later probe must lie in (27,66).
Probe 18 violates the inherited interval (27,66); the sequence is impossible.

The violated bound comes from an earlier ancestor. A later comparison cannot discard it: every node subsequently visited remains inside that ancestor’s chosen subtree. No choice of unvisited nodes can repair this path.

Original paper, page 7

Descriptive
Report issue

Locate a sorted-array minimum

Arrays & Linked Lists

Question 14(a), GATE 1996: An n×n integer array is intended to increase along every row and every column. Where is its minimum? The reproduction quantifies both inequalities only for i,j∈[1,n−1], which is narrower than full row/column sorting.
Question 14(a), GATE 1996: An n×n integer array is intended to increase along every row and every column. Where is its minimum? The reproduction quantifies both inequalities only for i,j∈[1,n−1], which is narrower than full row/column sorting.
Tap to enlarge
Answer & solution

Answer: Under the intended full row/column order: i=j=1. Under the literal restricted quantifier: not guaranteed. (no official key was published)

Under the standard partially sorted matrix interpretation, A[1,1]≤A[i,j] for every cell: move downward from (1,1) to (i,1), then rightward to (i,j), using monotonicity at each step. With strict comparisons and n>1 this makes A[1,1] the unique minimum; the requested blanks are i=1 and j=1. For n=1 the only cell is trivially the minimum.

There is a literal specification issue. The paper attach i,j∈[1,n−1] to both comparisons A[i,j]<A[i,j+1] and A[i,j]<A[i+1,j]. This does not constrain the last row horizontally or the last column vertically. In particular, A[n,n] appears in neither type of comparison. For n=2, the matrix [[1,2],[3,−100]] satisfies the printed comparisons 1<2 and 1<3, yet its minimum is at (2,2).

The usual intended definition instead quantifies horizontal comparisons for 1≤i≤n,1≤j<n, and vertical comparisons for 1≤i<n,1≤j≤n. The answer (1,1) follows from that corrected definition, not from the restricted literal one. This caveat also applies to the insertion procedure in the next subpart.

Original paper, page 8

Descriptive
Report issue

Restore a sorted matrix after insertion

Arrays & Linked Lists

Question 14(b), GATE 1996: Delete the smallest element of an n×n row- and column-increasing array. Insert x, smaller than every item of the last row and last column, in O(n) time. Complete: i:=1;j:=1;A[i,j]:=x; while (x>blank or x>blank) do if A[i+1,j]<blank then begin A[i,j]:=A[i+1,j];i:=i+1 end else begin blank end; A[i,j]:=blank. Assume the intended full monotonicity and distinct inserted value.
Question 14(b), GATE 1996: Delete the smallest element of an n×n row- and column-increasing array. Insert x, smaller than every item of the last row and last column, in O(n) time. Complete: i:=1;j:=1;A[i,j]:=x; while (x>blank or x>blank) do if A[i+1,j]<blank then begin A[i,j]:=A[i+1,j];i:=i+1 end else begin blank end; A[i,j]:=blank. Assume the intended full monotonicity and distinct inserted value.
Question 14(b), GATE 1996: Delete the smallest element of an n×n row- and column-increasing array. Insert x, smaller than every item of the last row and last column, in O(n) time. Complete: i:=1;j:=1;A[i,j]:=x; while (x>blank or x>blank) do if A[i+1,j]<blank then begin A[i,j]:=A[i+1,j];i:=i+1 end else begin blank end; A[i,j]:=blank. Assume the intended full monotonicity and distinct inserted value.
Tap to enlarge
Answer & solution

Answer: Compare x to A[i+1,j],A[i,j+1]; choose their minimum; shift it up/left; advance i or j; finally write x. (no official key was published)

A complete hole-moving version is:
i:=1; j:=1; A[i,j]:=x;
while (x>A[i+1,j]) or (x>A[i,j+1]) do
begin
  if A[i+1,j]<A[i,j+1] then
  begin A[i,j]:=A[i+1,j]; i:=i+1 end
  else
  begin A[i,j]:=A[i,j+1]; j:=j+1 end
end;
A[i,j]:=x.

Treat the current cell as a hole until the final assignment. If both children are greater than x, x belongs there. Otherwise the smaller of the downward and rightward neighbors is the smallest candidate that can fill the hole without violating either row or column order. Move it into the hole, advance to its old position, and repeat. Along the moved path, predecessors remain smaller than the element shifted into place; untouched cells preserve their old comparisons. The terminal hole receives x.

Each iteration increases i+j by one, hence there are O(n) iterations and O(1) extra storage. The given strict upper bound on x prevents the hole from entering the last row or last column: a boundary neighbor is greater than x and cannot be the smaller neighbor selected while the loop is true. Thus the two neighbor accesses are safe for n≥2. Without that promise use explicit bounds or +∞ sentinels.

Distinct x is a sufficient extra condition for preserving strict order. Without it the guarantee can fail: consider [[0,10,40],[20,30,50],[60,70,80]] with x=10. Here x is below every last-row/column entry, yet the procedure stops with adjacent equal values in the first row. Equal entries can sometimes occupy incomparable cells, but strict preservation is not guaranteed by the printed promise. If duplicates are allowed, interpret sorted as nondecreasing instead. Finally, the literal source quantifier omits boundary comparisons, so the algorithm relies on the intended full row/column definition discussed in part (a).

Original paper, page 8

Descriptive
Report issue

Identify linear-probing collisions

Hashing

Question 15(a), GATE 1996: Insert K,R,P,C,S,N,Y,T,J,M in that order into slots 0,…,9 using linear probing and h(x)=(ord(x)−ord('a')+1) mod10. The input is uppercase while the formula uses lowercase a; distinguish alphabet-position normalization from literal uppercase ASCII. Which insertions collide?
Question 15(a), GATE 1996: Insert K,R,P,C,S,N,Y,T,J,M in that order into slots 0,…,9 using linear probing and h(x)=(ord(x)−ord('a')+1) mod10. The input is uppercase while the formula uses lowercase a; distinguish alphabet-position normalization from literal uppercase ASCII. Which insertions collide?
Tap to enlarge
Answer & solution

Answer: J and M under either stated convention. (no official key was published)

With alphabet positions (equivalently lowercasing each character before applying the formula), the home slots are K1,R8,P6,C3,S9,N4,Y5,T0,J0,M3. The first eight insertions find empty slots. J collides at 0 with T and at 1 with K, then occupies 2. M collides at 3,4,5,6, occupied respectively by C,N,Y,P, then occupies 7. Thus J and M are exactly the insertions that encounter collisions.

The final normalized table is 0:T,1:K,2:J,3:C,4:N,5:Y,6:P,7:M,8:R,9:S. Every character appears once and all ten slots are filled.

For literal uppercase ASCII with the printed lowercase 'a', ord(uppercase)=ord(lowercase)−32. Therefore each home slot is shifted by −32≡−2 modulo 10. Linear probing is circular and the whole table rotates by the same amount. Homes become 9,6,4,1,7,2,3,8,8,1, and the final table is 0:J,1:C,2:N,3:Y,4:P,5:M,6:R,7:S,8:T,9:K. J and M still collide. This literal result uses mathematical nonnegative modulo; a language whose remainder operator returns negative values needs normalization before indexing. Neither the paper resolves the case/encoding convention, so both answers are disclosed rather than silently changing the formula.

Original paper, page 9

Descriptive
Report issue

Build the linear-probing table

Hashing

Question 15(b), GATE 1996: Insert K,R,P,C,S,N,Y,T,J,M in that order into slots 0,…,9 using linear probing and h(x)=(ord(x)−ord('a')+1) mod10. The input is uppercase while the formula uses lowercase a; distinguish alphabet-position normalization from literal uppercase ASCII. Give the final table.
Question 15(b), GATE 1996: Insert K,R,P,C,S,N,Y,T,J,M in that order into slots 0,…,9 using linear probing and h(x)=(ord(x)−ord('a')+1) mod10. The input is uppercase while the formula uses lowercase a; distinguish alphabet-position normalization from literal uppercase ASCII. Give the final table.
Tap to enlarge
Answer & solution

Answer: Alphabet positions: [T,K,J,C,N,Y,P,M,R,S]. Literal uppercase ASCII: [J,C,N,Y,P,M,R,S,T,K]. (no official key was published)

With alphabet positions (equivalently lowercasing each character before applying the formula), the home slots are K1,R8,P6,C3,S9,N4,Y5,T0,J0,M3. The first eight insertions find empty slots. J collides at 0 with T and at 1 with K, then occupies 2. M collides at 3,4,5,6, occupied respectively by C,N,Y,P, then occupies 7. Thus J and M are exactly the insertions that encounter collisions.

The final normalized table is 0:T,1:K,2:J,3:C,4:N,5:Y,6:P,7:M,8:R,9:S. Every character appears once and all ten slots are filled.

For literal uppercase ASCII with the printed lowercase 'a', ord(uppercase)=ord(lowercase)−32. Therefore each home slot is shifted by −32≡−2 modulo 10. Linear probing is circular and the whole table rotates by the same amount. Homes become 9,6,4,1,7,2,3,8,8,1, and the final table is 0:J,1:C,2:N,3:Y,4:P,5:M,6:R,7:S,8:T,9:K. J and M still collide. This literal result uses mathematical nonnegative modulo; a language whose remainder operator returns negative values needs normalization before indexing. Neither the paper resolves the case/encoding convention, so both answers are disclosed rather than silently changing the formula.

Original paper, page 9

1 mark · MCQ
Report issue

Leaves and binary branching nodes

Tree Properties & Traversals

Question 1.17, GATE 1995: A nonempty rooted binary tree has n leaves. How many nodes have two children?
Tap to enlarge
Your answer
Answer & solution

Answer: B: n−1 (no official key was published)

Let n0,n1,n2 count nodes with zero, one and two children. The tree has n0+n1+n2−1 edges because it is connected and acyclic. Counting edges by parents gives n1+2n2. Equating the two expressions yields n2=n0−1=n−1. Unary nodes cancel and therefore do not alter the relationship. Here degree two means two children, the rooted-tree convention; interpreting it as undirected graph degree would be a different question.

Original paper, page 2

Descriptive
Report issue

Repair an in-place transpose

Arrays & Linked Lists

Question 4(b), GATE 1995: An N×N integer array A (1<N≤20) is transposed by: for I:=1 to N−1 do for J:=1 to N do begin TMP:=A[I,J]; A[I,J]:=A[J,I]; A[J,I]:=TMP end. Find and correct the error.
Tap to enlarge
Answer & solution

Answer: Change the inner loop to J:=I+1 to N. (no official key was published)

Transposition must exchange each off-diagonal pair A[i,j], A[j,i] exactly once. In the supplied code, when i and j are both below N, the pair is exchanged once on iteration (i,j) and again on (j,i). The second exchange undoes the first. Pairs involving N are treated differently because the outer loop never reaches N. This is therefore not a valid general transpose, even though special inputs or N=2 can hide the fault.

Keep I from 1 through N−1 and change the inner loop to J from I+1 through N. The three assignments in the swap body can remain unchanged. Every unordered off-diagonal pair has exactly one representative with i<j, so it is visited once; diagonal entries need no work. The algorithm performs N(N−1)/2 swaps, takes Θ(N²) time and uses one temporary integer. Afterward every old A[i,j] has moved to A[j,i].

Original paper, page 6

Descriptive
Report issue

Enumerate postorder binary trees

Tree Properties & Traversals

Question 6, GATE 1995: How many ordered binary trees on three nodes have postorder A,B,C? Draw all of them.
Tap to enlarge
Answer & solution

Answer: 5 (no official key was published)

Postorder visits the left subtree, then the right subtree, then the root, so C must be the root. Partition the first two labels between its subtrees. If both subtrees are nonempty, each has one node: left A and right B. If only one subtree is nonempty, that subtree has postorder A,B, so its root is B and A can be either B’s left or right child. The two-node subtree itself can be C’s left or right child, giving four more trees.

A compact complete drawing uses node(left,right), with ∅ denoting an absent child:
1. C(A,B)
2. C(B(A,∅),∅)
3. C(B(∅,A),∅)
4. C(∅,B(A,∅))
5. C(∅,B(∅,A)).
Here A or B written without parentheses is a leaf. Each drawing emits A then B then C under postorder. The cases exhaust left-subtree sizes 0,1,2, giving the Catalan count C₃=C₀C₂+C₁C₁+C₂C₀=2+1+2=5. Left and right child positions are distinguished; these are not restricted to full binary trees.

Original paper, page 6

Report issue

Packing a lower triangular matrix

Arrays & Linked Lists

Question 1.11, GATE 1994: Rows of a lower triangular n×n matrix, including their diagonal, are stored consecutively. With one-based indices, where is entry (i,j), j≤i?
Tap to enlarge
Your answer
Answer & solution

Answer: C: i(i−1)/2+j (no official key was published)

Before row i, the stored rows have lengths 1,2,…,i−1, totaling i(i−1)/2 entries. Entry j in the next row is j positions beyond that prefix under one-based indexing. Therefore its packed index is i(i−1)/2+j. A zero-based packed offset would subtract one from this result. The formula stores every position in the lower triangle, even if a particular value happens to be zero; omitting actual zeros would require additional sparse-matrix metadata.

Original paper, page 2

Report issue

A stack permutation

Stacks & Queues

Question 1.14, GATE 1994: Input 1,2,3,4,5 arrives in order. Which output is possible with one stack: 34512,34521,15234,54312?
Tap to enlarge
Your answer
Answer & solution

Answer: B: 34521 (no official key was published)

Step through it (4 options)

Push 1,2,3 and pop 3; push 4 and pop 4; push 5 and pop 5; then pop 2 and 1. This constructs 34521. For 34512, after producing 345 the stack has 2 above 1, so 1 cannot come next. For 15234, after popping 1 then pushing through 5, the next available value is 4, not 2. For 54312, after popping 5,4,3, value 2 still blocks 1. Thus only B is feasible.

Original paper, page 2

Report issue

Where linked lists are unsuitable

Arrays & Linked Lists

Question 1.17, GATE 1994: Among insertion sort, binary search, radix sort and polynomial manipulation, which is poorly supported by a plain linked list?
Tap to enlarge
Your answer
Answer & solution

Answer: B: binary search (no official key was published)

Binary search repeatedly accesses a midpoint by index. An array provides that access in constant time, but a plain linked list must traverse links to locate it, losing the logarithmic-access advantage. Linked lists can support insertion-sort splicing, bucket chains in radix sorting and sparse polynomial terms naturally. The issue is not that binary-search comparisons are impossible on a list, but that the necessary positional access is inefficient without additional indexing structures.

Original paper, page 2

Descriptive
Report issue

Reconstruction from preorder and postorder

Tree Properties & Traversals

Question 8, GATE 1994: A rooted tree has nodes numbered 1 to 12 in preorder. Its postorder is 3,5,4,2,7,8,6,10,11,12,9,1. Reconstruct it, give every parent, and show the tree.
Tap to enlarge
Answer & solution

Answer: Parents: 1:none; 2:1; 3:2; 4:2; 5:4; 6:1; 7:6; 8:6; 9:1; 10:9; 11:9; 12:9. (no official key was published)

1. The final postorder entry 1 is the root. The next preorder value 2 starts its first child subtree; that subtree ends at 2 in postorder, so it contains {2,3,4,5}.

2. Within subtree 2, node 3 is first and is already a complete subtree. The next child 4 has postorder 5,4 and therefore child 5.

3. The next unused preorder node is 6. Its postorder block is 7,8,6, giving children 7 and 8.

4. The remaining child subtree of 1 is rooted at 9 and has leaves 10,11,12.

5. These are ordered children according to the given traversals. A general rooted tree is intended, not a binary-tree constraint.

Diagram / structural description

1
├─2
│ ├─3
│ └─4
│   └─5
├─6
│ ├─7
│ └─8
└─9
  ├─10
  ├─11
  └─12

Original paper, page 5

Descriptive
Report issue

B+ tree insertion and splitting

B-Trees & Multiway Search Trees

Question 14(a), GATE 1994: Consider the B+ tree: The root has separators [25,38,69,93] and five linked leaves, left to right: [10,15], [25,36], [39,41,47], [69,71,75,83], [95,99,101,105]. Each node holds d to 2d keys, subject to the usual root exception. GFG asks for the tree after inserting 100; GateForum omits the insertion key.
Question 14(a), GATE 1994: Consider the B+ tree: The root has separators [25,38,69,93] and five linked leaves, left to right: [10,15], [25,36], [39,41,47], [69,71,75,83], [95,99,101,105]. Each node holds d to 2d keys, subject to the usual root exception. GFG asks for the tree after inserting 100; GateForum omits the insertion key.
Question 14(a), GATE 1994: Consider the B+ tree: The root has separators [25,38,69,93] and five linked leaves, left to right: [10,15], [25,36], [39,41,47], [69,71,75,83], [95,99,101,105]. Each node holds d to 2d keys, subject to the usual root exception. GFG asks for the tree after inserting 100; GateForum omits the insertion key.
Tap to enlarge
Answer & solution

Answer: For insertion of 100 with d=2 and splitting rather than redistribution: new root [69], internal children [25,38] and [93,100], with six leaves listed in the diagram. (no official key was published)

1. The four-key leaf requires 2d≥4, so d≥2. The two-key leaves require d≤2. Together these bounds establish d=2 and capacity 2d=4. Insert 100 into [95,99,101,105] to get five sorted keys [95,99,100,101,105].

2. Choose the legal split [95,99] and [100,101,105]. Copy separator 100 into the parent, which becomes [25,38,69,93,100] with six children.

3. The overflowing internal root splits around its middle separator 69. Promote 69 into a new root, leaving internal nodes [25,38] and [93,100], each with three children.

4. All six leaves remain at equal depth and hold between two and four keys. Keys in internal nodes are routing separators, not additional data records.

5. A 3/2 leaf split with separator 101 is also legal if that split convention is used. The problem does not state a tie-breaking split policy; present the selected valid construction rather than claim uniqueness.

Diagram / structural description

Root [69]
  Left internal [25,38] → [10,15] | [25,36] | [39,41,47]
  Right internal [93,100] → [69,71,75,83] | [95,99] | [100,101,105]

All six leaves are linked in the displayed order.

  • The source root contains 38 and 93, although the corresponding right leaves start with 39 and 95. These are valid lower routing boundaries under a separator-range convention; an exact-minimum convention would require 39 and 95 instead. Preserve the source and disclose the convention.

Original paper, page 6

Descriptive
Report issue

B+ tree search height

B-Trees & Multiway Search Trees

Question 14(b), GATE 1994: A B+ tree of order d holds d to 2d keys per node. For n leaf nodes, fill the order of the number of nodes accessed during a search.
Question 14(b), GATE 1994: A B+ tree of order d holds d to 2d keys per node. For n leaf nodes, fill the order of the number of nodes accessed during a search.
Question 14(b), GATE 1994: A B+ tree of order d holds d to 2d keys per node. For n leaf nodes, fill the order of the number of nodes accessed during a search.
Tap to enlarge
Answer & solution

Answer: O(1+log_(d+1) n); commonly written O(log_d n) for d≥2 and nontrivial trees. (no official key was published)

1. An internal non-root node has at least d+1 children because keys separate child ranges. A root that is internal has at least two children.

2. If the root-to-leaf distance is h≥1, there are at least 2(d+1)h−1 leaves. Rearranging bounds h by 1+logd+1(n/2).

3. Search follows a single child at each internal level and accesses the leaf, for h+1 node accesses. The extra constant handles n=1.

4. For d≥2, changing the logarithm base from d+1 to d changes only a bounded factor; logd n is the conventional blank. When d=1, logd n is undefined, so the d+1 expression is safer.

Original paper, page 6

5 marks · Descriptive
Report issue

Queue-to-stack transfer preserving front order

Stacks & Queues

Question 26, GATE 1994: A queue Q contains n items and stack S is empty. Move all items into S so the original queue front is the stack top, with all remaining relative order preserved. Use only queue Delete/Insert and stack Push/Pop, O(n) time and O(1) extra storage.
Tap to enlarge
Answer & solution

Answer: Transfer Q→S, then S→Q, then Q→S; use three n-iteration loops. (no official key was published)

Use a single item variable x and a loop counter. First repeat n times: x:=Delete(Q); Push(S,x). Next repeat n times: x:=Pop(S); Insert(Q,x). Finally repeat n times: x:=Delete(Q); Push(S,x). Here Delete removes the queue front, Insert appends at its rear, Push adds at the stack top, and Pop removes the top. No direct indexing or knowledge of either implementation is needed.

Let the original queue, from front to rear, be q1,q2,…,qn. After the first pass Q is empty and S is qn,…,q2,q1 from top to bottom, because each successive pushed item covers the previous one. The second pass pops in that reversed order and enqueues it, producing Q front-to-rear qn,…,q2,q1 and leaving S empty. The third pass reverses that queue order once more on the stack, leaving S top-to-bottom q1,q2,…,qn, exactly as required, and Q empty.

There are six primitive operations per item across the three passes, hence 6n operations and O(n) time under the usual constant-time ADT operations. Only x and counters are additional storage. The originally supplied queue and stack are reused rather than allocating another container. Recursively popping and pushing could also reverse an order but would consume O(n) call-stack storage and would violate the additional-space condition. The empty case performs no operations and already meets the postcondition.

Original paper, page 7

5 marks · Descriptive
Report issue

Insert before a singly linked-list node

Arrays & Linked Lists

Question 13, GATE 1993: A singly linked list contains d1,...,dn. X points to node j (1<=j<=n). A new node Y contains item d. Give an insertion algorithm without using the header. Both inspected reproductions print a desired sequence d1,...,d(j-1),dj,...,dn that omits the new d; the intended insert-before-X sequence d1,...,d(j-1),d,dj,...,dn is used below as an explicit interpretation.
Tap to enlarge
Answer & solution

Answer: Exchange X.data and Y.data, then set Y.next=X.next and X.next=Y; conditional on the intended insert-before-X interpretation and movable data. (no official key was published)

Without a predecessor pointer or access to the header, ordinary link insertion immediately before the physical node X is unavailable. But the requested data sequence can be achieved by exchanging data with the fresh node and linking that node after X. Assume X is non-null, Y is a fresh detached node distinct from all current nodes, and data fields may be copied:

procedure insert_before_by_value(X,Y):
    temp := X.data
    X.data := Y.data
    Y.data := temp
    Y.next := X.next
    X.next := Y

Initially X contains dj and Y contains d. After the exchange X contains d and Y contains dj. Y.next is then set to the former successor of X, and X.next is changed to Y. The local chain is now predecessor -> X(d) -> Y(dj) -> old successor. All nodes preceding X remain unchanged; any header already pointing to X still points to the first node. Therefore the data sequence becomes exactly the interpreted target. Saving the old successor before overwriting X.next is essential; reversing the last two operations would set Y.next=Y and create a cycle.

This also handles j=1 without changing the header, because X remains the physical first node but now carries d. For j=n, the old successor is null, so Y becomes the new last node. There are a constant number of field operations, giving O(1) time and O(1) extra space.

The method preserves value order, not node-to-value identity: an external pointer to X will now observe d, and dj moves to Y. If data cannot be moved or the physical new node Y must precede X, the supplied information is insufficient in a singly linked list, particularly when X is the head. That stronger requirement needs header/predecessor access or a changed representation. Finally, the printed sequence itself contains no d, so it cannot literally describe successful insertion; the source defect is retained rather than represented as a verified correction.

Original paper, page 11

Report issue

Internal nodes of a 2–3 tree

B-Trees & Multiway Search Trees

Question 2(vii), GATE 1992: A 2–3 tree has nine leaves, all at equal depth, and every internal node has two or three children. Which internal counts 4, 5, 6, 7 are possible?
Question 2(vii), GATE 1992: A 2–3 tree has nine leaves, all at equal depth, and every internal node has two or three children. Which internal counts 4, 5, 6, 7 are possible?
Tap to enlarge
Select all that apply
Answer & solution

Answer: A, D: 4 and 7 (no official key was published)

At height two, the root must have three children and each must have three leaves, giving 1+3=4 internal nodes and nine leaves. At height three, nine leaves require four parents at the deepest internal level, since five would already require ten leaves. The preceding level must therefore have two nodes with two children each, and the root has those two children. Internal count is 1+2+4=7; give one deepest node three leaves and the others two to get nine. Greater height needs at least sixteen leaves. Thus counts 5 and 6 cannot fit the equal-depth constraint.

Original paper, page 2

Descriptive
Report issue

Constant-time set membership

Arrays & Linked Lists

Question 9(i), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give MEMBER(x) using the common representation.
Question 9(i), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give MEMBER(x) using the common representation.
Question 9(i), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give MEMBER(x) using the common representation.
Tap to enlarge
Answer & solution

Answer: Use inverse-position array: MEMBER(x) returns pos[x]≠0. (no official key was published)

Use two length-n arrays: dense[1..m] stores precisely the current set in arbitrary order; pos[x] is x’s dense position if present, otherwise 0. The invariant is pos[dense[j]]=j for 1≤j≤m, and pos[x]=0 exactly for absent elements. Initialize m:=0 and pos[1..n]:=0, which takes Θ(n) time once. dense need not be initialized because only its active prefix is read. Space is Θ(n). Array indexing, integer comparison and assignment are constant-time in the word-RAM model, with words large enough for 0..n. Operations assume 1≤x≤n or reject out-of-range x before indexing.

Pictorial example, n=7 and S={2,5,7}:
dense positions: 1  2  3 | 4 5 6 7
dense values:    2  5  7 | unused
pos index:      1  2  3  4  5  6  7
pos value:      0  1  0  0  2  0  3

m=3; arrows are 2→1, 5→2, 7→3. A plain Boolean array gives easy membership but could require Θ(n) scanning to FIND-ONE; the dense prefix supplies an immediate element. Set order is deliberately not preserved, which enables constant-time deletion.

MEMBER(x):
  if x<1 or x>n then return false;
  return pos[x]<>0.

The initialization and update invariant make a nonzero position an exact certificate of membership. In the pictured set MEMBER(5)=true because pos[5]=2, whereas MEMBER(4)=false because pos[4]=0. The routine performs only a fixed number of comparisons and one array access, so its worst-case cost is O(1), regardless of the number of stored elements. All later ADD and DELETE operations must preserve the inverse links; membership must not read uninitialized pos entries. The stipulated one-time Θ(n) initialization is not being hidden as an O(1) operation.

Original paper, page 6

Descriptive
Report issue

Find an arbitrary set element

Arrays & Linked Lists

Question 9(ii), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give FIND-ONE(S) using the common representation.
Question 9(ii), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give FIND-ONE(S) using the common representation.
Question 9(ii), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give FIND-ONE(S) using the common representation.
Tap to enlarge
Answer & solution

Answer: If m=0 return EMPTY; otherwise return dense[1]. (no official key was published)

Use two length-n arrays: dense[1..m] stores precisely the current set in arbitrary order; pos[x] is x’s dense position if present, otherwise 0. The invariant is pos[dense[j]]=j for 1≤j≤m, and pos[x]=0 exactly for absent elements. Initialize m:=0 and pos[1..n]:=0, which takes Θ(n) time once. dense need not be initialized because only its active prefix is read. Space is Θ(n). Array indexing, integer comparison and assignment are constant-time in the word-RAM model, with words large enough for 0..n. Operations assume 1≤x≤n or reject out-of-range x before indexing.

Pictorial example, n=7 and S={2,5,7}:
dense positions: 1  2  3 | 4 5 6 7
dense values:    2  5  7 | unused
pos index:      1  2  3  4  5  6  7
pos value:      0  1  0  0  2  0  3

m=3; arrows are 2→1, 5→2, 7→3. A plain Boolean array gives easy membership but could require Θ(n) scanning to FIND-ONE; the dense prefix supplies an immediate element. Set order is deliberately not preserved, which enables constant-time deletion.

FIND-ONE():
  if m=0 then return EMPTY;
  return dense[1].

EMPTY is a distinguished failure result, for example 0 because the universe is 1..n. In the displayed example the answer is 2. Returning dense[m]=7 would be equally valid; the question does not require the minimum, maximum or any particular order.

The dense-prefix invariant says every entry between 1 and m is a member, and m=0 exactly characterizes the empty set. Hence the result is valid when nonempty and the routine never reads an inactive or uninitialized cell. It requires one test and at most one array lookup, yielding worst-case O(1). Returning a remembered arbitrary element without maintaining its validity on DELETE would not suffice; the companion deletion routine keeps the prefix compact and therefore maintains this guarantee.

Original paper, page 6

Descriptive
Report issue

Constant-time set insertion

Arrays & Linked Lists

Question 9(iii), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give ADD(x) using the common representation.
Question 9(iii), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give ADD(x) using the common representation.
Question 9(iii), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give ADD(x) using the common representation.
Tap to enlarge
Answer & solution

Answer: If pos[x]=0, append x to dense and set pos[x] to the new m; otherwise do nothing. (no official key was published)

Use two length-n arrays: dense[1..m] stores precisely the current set in arbitrary order; pos[x] is x’s dense position if present, otherwise 0. The invariant is pos[dense[j]]=j for 1≤j≤m, and pos[x]=0 exactly for absent elements. Initialize m:=0 and pos[1..n]:=0, which takes Θ(n) time once. dense need not be initialized because only its active prefix is read. Space is Θ(n). Array indexing, integer comparison and assignment are constant-time in the word-RAM model, with words large enough for 0..n. Operations assume 1≤x≤n or reject out-of-range x before indexing.

Pictorial example, n=7 and S={2,5,7}:
dense positions: 1  2  3 | 4 5 6 7
dense values:    2  5  7 | unused
pos index:      1  2  3  4  5  6  7
pos value:      0  1  0  0  2  0  3

m=3; arrows are 2→1, 5→2, 7→3. A plain Boolean array gives easy membership but could require Θ(n) scanning to FIND-ONE; the dense prefix supplies an immediate element. Set order is deliberately not preserved, which enables constant-time deletion.

ADD(x):
  require 1<=x<=n;
  if pos[x]=0 then begin
    m:=m+1;
    dense[m]:=x;
    pos[x]:=m
  end.

Sets do not contain duplicate elements, so the initial presence test is essential. If x is already present, returning without changes preserves the representation. If it is absent, adding a new dense entry and its inverse position establishes the invariant for x without changing any existing entry. Since an absent x exists in a universe of size n, m<n before the increment; the append cannot exceed capacity.

For example ADD(4) changes dense [2,5,7] to [2,5,7,4], changes pos[4] from 0 to 4, and changes m from 3 to 4; all other positions stay fixed. ADD(5) thereafter changes nothing. There is no search, shifting or allocation during an operation because storage was reserved at initialization. The fixed number of reads/writes gives worst-case O(1), not merely amortized O(1).

Original paper, page 6

Descriptive
Report issue

Constant-time swap deletion

Arrays & Linked Lists

Question 9(iv), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give DELETE(x) using the common representation.
Question 9(iv), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give DELETE(x) using the common representation.
Question 9(iv), GATE 1992: Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give DELETE(x) using the common representation.
Tap to enlarge
Answer & solution

Answer: Replace x in dense by its last element, repair that element’s inverse position, shorten m and clear pos[x]. (no official key was published)

Use two length-n arrays: dense[1..m] stores precisely the current set in arbitrary order; pos[x] is x’s dense position if present, otherwise 0. The invariant is pos[dense[j]]=j for 1≤j≤m, and pos[x]=0 exactly for absent elements. Initialize m:=0 and pos[1..n]:=0, which takes Θ(n) time once. dense need not be initialized because only its active prefix is read. Space is Θ(n). Array indexing, integer comparison and assignment are constant-time in the word-RAM model, with words large enough for 0..n. Operations assume 1≤x≤n or reject out-of-range x before indexing.

Pictorial example, n=7 and S={2,5,7}:
dense positions: 1  2  3 | 4 5 6 7
dense values:    2  5  7 | unused
pos index:      1  2  3  4  5  6  7
pos value:      0  1  0  0  2  0  3

m=3; arrows are 2→1, 5→2, 7→3. A plain Boolean array gives easy membership but could require Θ(n) scanning to FIND-ONE; the dense prefix supplies an immediate element. Set order is deliberately not preserved, which enables constant-time deletion.

DELETE(x):
  require 1<=x<=n;
  k:=pos[x];
  if k=0 then return;
  y:=dense[m];
  dense[k]:=y;
  pos[y]:=k;
  m:=m-1;
  pos[x]:=0.

The position array directly locates x, avoiding a search. Moving the final member into x’s slot avoids shifting the remaining members. Updating pos[y] repairs the one inverse link affected by the move. The shortened prefix contains all old members except x, and clearing pos[x] makes future membership queries false.

Example DELETE(5) on dense [2,5,7] moves 7 from position 3 to position 2. The new active prefix is [2,7], m=2, pos[7]=2 and pos[5]=0. The old dense[3] value is irrelevant because it lies outside the prefix. If x already is the final element, then y=x; the self-assignment is harmless and the last assignment pos[x]:=0 is essential. The same code safely empties a singleton set. Deleting an absent element leaves everything unchanged. Only a fixed number of assignments and lookups are performed, proving worst-case O(1).

Original paper, page 6

2 marks · Other
Report issue

Weighted external path length

Tree Properties & Traversals

Question 1(viii), GATE 1991: Leaves of weights 2, 4, 5, 7 have depth 4; weights 9, 10 have depth 3; weight 15 has depth 1 in the source binary tree. Find its weighted external path length.
Question 1(viii), GATE 1991: Leaves of weights 2, 4, 5, 7 have depth 4; weights 9, 10 have depth 3; weight 15 has depth 1 in the source binary tree. Find its weighted external path length.
Tap to enlarge
Answer & solution

Answer: 144 (no official key was published)

External path length weights each leaf by the number of edges from the root, with root depth zero. Grouping equal depths gives 4(2+4+5+7)+3(9+10)+1(15). The sums are 4×18=72, 3×19=57, and 15, totaling 144. Internal unlabeled nodes contribute nothing to this external measure. Counting vertices instead of edges would add the sum of leaf weights, so the conventional edge-depth definition is essential. The supplied depth list is a transcription of the inspected tree, not a newly constructed tree.

Original paper, page 1

2 marks · Other
Report issue

Inorder traversal of the displayed tree

Tree Properties & Traversals

Question 1(ix), GATE 1991: Root 7 has left child 1 with children 4, 6 and right child 3 with right child 5; node 5 has children 2, 8. Give inorder traversal.
Question 1(ix), GATE 1991: Root 7 has left child 1 with children 4, 6 and right child 3 with right child 5; node 5 has children 2, 8. Give inorder traversal.
Tap to enlarge
Answer & solution

Answer: 4, 1, 6, 7, 3, 2, 5, 8 (no official key was published)

Inorder recursively visits left subtree, node, then right subtree. The subtree rooted at 1 therefore gives 4, 1, 6. Next visit root 7. Node 3 has no left child, so visit 3 immediately, then traverse its right child 5 as 2, 5, 8. Concatenating gives 4, 1, 6, 7, 3, 2, 5, 8. The numeric labels are merely node names; this is not a binary search tree, and sorting the labels would not be a traversal. Every node appears exactly once.

Original paper, page 1

2 marks · MSQ
Report issue

Tracing stack operations

Stacks & Queues

Question 3(vii), GATE 1991: Execute PUSH 10, PUSH 20, POP, PUSH 10, PUSH 20, POP, POP, POP, PUSH 20, POP. Options include A20, 10, 20, 10, 20; B20, 20, 10, 10, 20; C10, 20, 20, 10, 20; D20, 20, 10, 20, 10.
Question 3(vii), GATE 1991: Execute PUSH 10, PUSH 20, POP, PUSH 10, PUSH 20, POP, POP, POP, PUSH 20, POP. Options include A20, 10, 20, 10, 20; B20, 20, 10, 10, 20; C10, 20, 20, 10, 20; D20, 20, 10, 20, 10.
Tap to enlarge
Select all that apply
Answer & solution

Answer: B: 20, 20, 10, 10, 20 (no official key was published)

Step through it (12 steps)

After the first two pushes, the stack from bottom to top is [10, 20], so the first pop yields 20. Pushing 10 then 20 leaves [10, 10, 20]; the next three pops yield 20, 10, 10 and empty the stack. The final push/pop yields 20. Concatenating these five outputs gives 20, 20, 10, 10, 20. No pop is attempted on an empty stack. The result follows last-in-first-out order, not the chronological order of pushes as a queue would use.

Original paper, page 3

2 marks · Descriptive
Report issue

Optimal search tree for three equally likely identifiers

Binary Search & Balanced Trees

Question 4(iii), GATE 1991: Construct an optimal binary search tree for ordered identifiers if, stop, while with equal successful-search probabilities.
Question 4(iii), GATE 1991: Construct an optimal binary search tree for ordered identifiers if, stop, while with equal successful-search probabilities.
Tap to enlarge
Answer & solution

Answer: Root stop; left child if; right child while (no official key was published)

The alphabetic order is if<stop<while. Placing the middle identifier at the root preserves search-tree ordering with the other two as its children. Successful search takes one comparison at the root and two at either child, for mean (1+2+2)/3=5/3. Any endpoint root forces the remaining two into one subtree, creating depths corresponding to comparison counts 1, 2, 3 and mean 2. Thus the balanced tree is optimal. The calculation uses equal successful-search probabilities; unspecified unequal unsuccessful-search gap weights would define a different optimization problem.

Original paper, page 5

1 mark · Descriptive
Report issue

Identifying the tree structure

Heaps & Priority Queues

Question 14(a), GATE 1991: The complete binary tree has level-order array [1,5,18,7,13,25,20,11,9,15,17,27]. Its edges are 1→(5,18), 5→(7,13), 18→(25,20), 7→(11,9), 13→(15,17), and 25→(27,left only). Identify the data structure.
Question 14(a), GATE 1991: The complete binary tree has level-order array [1,5,18,7,13,25,20,11,9,15,17,27]. Its edges are 1→(5,18), 5→(7,13), 18→(25,20), 7→(11,9), 13→(15,17), and 25→(27,left only). Identify the data structure.
Question 14(a), GATE 1991: The complete binary tree has level-order array [1,5,18,7,13,25,20,11,9,15,17,27]. Its edges are 1→(5,18), 5→(7,13), 18→(25,20), 7→(11,9), 13→(15,17), and 25→(27,left only). Identify the data structure.
Tap to enlarge
Answer & solution

Answer: A binary min-heap. (no official key was published)

Two separate conditions identify this tree. First, its shape is complete: all levels above the last are full and the last level fills from left to right. Second, every parent is no greater than either child: for example 1≤5,18; 5≤7,13; 18≤25,20; and 7≤11,9. The minimum element is therefore at the root, and the tree is a binary min-heap.

It is not a binary search tree. For instance, the root's left subtree contains 5 even though 5>1, and the left child 25 of node 18 exceeds its parent. A heap imposes parent-child order but imposes no sorted order between siblings or across unrelated subtrees. The level-order array in the prompt fully specifies the source figure and provides the customary compact heap representation.

Original paper, page 8

2 marks · Descriptive
Report issue

Deleting key five from the min-heap

Heaps & Priority Queues

Question 14(b), GATE 1991: The complete binary tree has level-order array [1,5,18,7,13,25,20,11,9,15,17,27]. Its edges are 1→(5,18), 5→(7,13), 18→(25,20), 7→(11,9), 13→(15,17), and 25→(27,left only). Show the steps deleting key 5 while retaining the structure.
Question 14(b), GATE 1991: The complete binary tree has level-order array [1,5,18,7,13,25,20,11,9,15,17,27]. Its edges are 1→(5,18), 5→(7,13), 18→(25,20), 7→(11,9), 13→(15,17), and 25→(27,left only). Show the steps deleting key 5 while retaining the structure.
Question 14(b), GATE 1991: The complete binary tree has level-order array [1,5,18,7,13,25,20,11,9,15,17,27]. Its edges are 1→(5,18), 5→(7,13), 18→(25,20), 7→(11,9), 13→(15,17), and 25→(27,left only). Show the steps deleting key 5 while retaining the structure.
Tap to enlarge
Answer & solution

Answer: Replace 5 with last key 27, remove the last leaf, then swap 27 with 7 and with 9. Final array [1,7,18,9,13,25,20,11,27,15,17]. (no official key was published)

Use one-based array indexing. Key 5 is at index 2 and the last node, key 27, is at index 12. Delete the last node and place its value at index 2. Taking the last leaf preserves the complete-tree shape; simply removing node 5 would leave a hole.

After replacement:
[1,27,18,7,13,25,20,11,9,15,17]

The new key is greater than both children 7 and 13. Swap with the smaller child 7 (index 4), not an arbitrary child:
[1,7,18,27,13,25,20,11,9,15,17]

At index 4, children are 11 and 9. Swap 27 with the smaller, 9 (index 9):
[1,7,18,9,13,25,20,11,27,15,17]

Index 9 is a leaf, so stop. Each swap makes the parent of the affected subtree its minimum, and only the downward path can remain out of order. The final tree has levels [1], [7,18], [9,13,25,20], [11,27,15,17]; every parent-child inequality and the complete shape are preserved.

Original paper, page 8

3 marks · Descriptive
Report issue

Deleting any min-heap node

Heaps & Priority Queues

Question 14(c), GATE 1991: The complete binary tree has level-order array [1,5,18,7,13,25,20,11,9,15,17,27]. Its edges are 1→(5,18), 5→(7,13), 18→(25,20), 7→(11,9), 13→(15,17), and 25→(27,left only). Give pseudocode to delete an arbitrary node of an n-node min-heap, with worst-case complexity. Distinguish a supplied node index from a supplied key.
Question 14(c), GATE 1991: The complete binary tree has level-order array [1,5,18,7,13,25,20,11,9,15,17,27]. Its edges are 1→(5,18), 5→(7,13), 18→(25,20), 7→(11,9), 13→(15,17), and 25→(27,left only). Give pseudocode to delete an arbitrary node of an n-node min-heap, with worst-case complexity. Distinguish a supplied node index from a supplied key.
Question 14(c), GATE 1991: The complete binary tree has level-order array [1,5,18,7,13,25,20,11,9,15,17,27]. Its edges are 1→(5,18), 5→(7,13), 18→(25,20), 7→(11,9), 13→(15,17), and 25→(27,left only). Give pseudocode to delete an arbitrary node of an n-node min-heap, with worst-case complexity. Distinguish a supplied node index from a supplied key.
Tap to enlarge
Answer & solution

Answer: Replace the node by the last key and sift up or down as needed. Known-index deletion costs O(log n); locating an arbitrary key can add Θ(n). (no official key was published)

Assume a one-based array H[1..n] and a valid index p. Replacing H[p] by H[n] and shortening the array preserves completeness. The replacement may be smaller than its parent or larger than a child, so a general deletion cannot always use only sift-down.

DELETE_AT(H,n,p):
  require 1 <= p <= n
  if p == n: return n-1
  H[p] := H[n]
  n := n-1
  if p > 1 and H[p] < H[floor(p/2)]:
    while p > 1 and H[p] < H[floor(p/2)]:
      swap H[p], H[floor(p/2)]
      p := floor(p/2)
  else:
    while 2*p <= n:
      c := 2*p
      if c+1 <= n and H[c+1] < H[c]: c := c+1
      if H[p] <= H[c]: break
      swap H[p], H[c]
      p := c
  return n

Only inequalities incident to the replaced node can initially fail. If the replacement is less than its parent, it is also less than the old children, since those children were at least the old value, which was at least the parent. Thus only upward repair is needed. Otherwise the parent relation holds, and downward repair with the smaller child fixes each level without creating a violation above. Equal values need no swap.

A complete binary tree has height floor(log2 n). Either repair traverses at most that many levels and uses O(1) extra space, so a supplied-index deletion is O(log n) worst case. If only a key is supplied and no key-to-index directory exists, a heap is not a search tree: finding the occurrence can cost Θ(n), making the entire deletion Θ(n) worst case. A maintained locator can remove that search cost but must be updated on swaps and handle duplicates explicitly.

Original paper, page 8