I had an interesting job interview experience a while back. The question started really easy:
Q1: We have a bag containing numbers
May be this algorithm can work for question 1:
Or even better:
def GetValue(A)
val=0
for i=1 to 100
do
val=val^i
done
for value in A:
do
val=val^value
done
return val
This algorithm can in fact be expanded for two missing numbers. The first step remains the same. When we call GetValue with two missing numbers the result will be a a1^a2
are the two missing numbers. Lets say
val = a1^a2
Now to sieve out a1 and a2 from val we take any set bit in val. Lets say the ith
bit is set in val. That means that a1 and a2 have different parity at ith
bit position.
Now we do another iteration on the original array and keep two xor values. One for the numbers which have the ith bit set and other which doesn't have the ith bit set. We now have two buckets of numbers, and its guranteed that a1 and a2
will lie in different buckets. Now repeat the same what we did for finding one missing element on each of the bucket.