GATE / CS ARCHIVE

GATE CSE 2000 / QUESTION 15(a)

Trace sparse-set initialization

Data Structures · Arrays & Linked Lists · Full GATE CSE 2000 paper

GATE 2000, Q15(a) Descriptive
Report issue

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