GATE / CS ARCHIVE

GATE CSE 1992 / QUESTION 9(i)

Constant-time set membership

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

GATE 1992, Q9(i) Descriptive
Report issue

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