GATE / CS ARCHIVE

SUBJECT COLLECTION

Data Structures · Arrays & Linked Lists

33 questions, newest first

GATE CSE has asked 33 questions on Arrays & Linked Lists (Data Structures) from 1992 to 2025, in 21 of the 46 papers; the most recent is in GATE CSE 2025 Set 1. In the last five years it carried 0.5 marks per 100-mark paper on average, against 0.4 since 2003. Since 2014 the questions have been 6 MCQ and 1 NAT.

Browse topics
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

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

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

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 · 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 · 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 · 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

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

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

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 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

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

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

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

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

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

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

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

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

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

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

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