Problem:
Design a data structure that allows one to search, insert, and delete an integer
X in O(1) time (i.e. , constant time, independent of the total number of integersstored). Assume that 1 ≤ X ≤ n and that there are m+n units of space available,
where m is the maximum number of integers that can be in the table at any one
time. (Hint: use two arrays A[1..n] and B[1..m].) You are not allowed to initialize
either A or B, as that would take O(m) or O(n) operations. This means the arrays
are full of random garbage to begin with, so you must be very careful.
Solution:
With an additional variable recording the size of the container.
To insert x, search x first
if size==m, return;
if x exists, return.
if x not exists, set A[x] = size, B[size]=x, size++,;
To search x
if A[x] > size, return false;
if B[A[x]] == x, return true;
To delete x
if A[x] > size, return false;
if B[A[x]] == x, A[x] = -1, B[A[x]]=-1;
Fallbacks:
For the above implementation, the container can only insert m times. If someone delete and inserts again when the container is full, it won't accept that value.
To reuse the wholes in B, we have to iterate m to look for holes, resulting in a O(m) time.