GATE / CS ARCHIVE

GATE CSE 1992 / QUESTION 9(ii)

Find an arbitrary set element

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

GATE 1992, Q9(ii) Descriptive
Report issue

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