Arrays & Linked Lists



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 3m=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).