i have following problem from book introduction algorithm second edition by MIT university
problem is following
An array A[1 . . n] contai
Call your missing number M
.
You can split your array into two parts depending on whether the least significant bit of A[i]
is a 1 or a 0. The smaller of the two parts (call it P_1
) is at most (n-1)/2
elements in size, and it tells you whether M
's least significant bit is a 1 or a 0.
Now consider the 2nd bit for the elements of P_1
. Again, this part can be split in two, and the smaller of the two parts (P_2
) tells you whether this bit should be a 1 or a 0.
Carry on going (P_3
, P_4
, ...) until you've worked out what all the bits are.
You can prove that this is O(n)
because you are essentially looking at n + n/2 + n/4 + ...
different individual bits in your array, and this sum is less than 2n
.
Here is a Python implementation:
def bit_at(n, bit):
return (n>>bit) & 1
def find_missing(a, bits):
indexes = range(len(a))
missing = 0
for bit in range(bits):
ones = [i for i in indexes if bit_at(a[i], bit)==1]
zeroes = [i for i in indexes if bit_at(a[i], bit)==0]
if len(ones) <= len(zeroes):
indexes = ones
missing |= (1<<bit)
else:
indexes = zeroes
return missing
print find_missing([7,2,6,4,1,5,0], 3)