views:

86

answers:

1

i have following problem from book introduction algorithm second edition by MIT university

problem is following

An array A[1 . . n] contains all the integers from 0 to n except one. It would be easy to determine the missing integer in O(n) time by using an auxiliary array B[0 . . n] to record which numbers appear in A. In this problem, however, we cannot access an entire integer in A with a single operation. The elements of A are represented in binary, and the only operation we can use to access them is “fetch the j th bit of A[i],” which takes constant time.

Show that if we use only this operation, we can still determine the missing integer in O(n) time

please help

+3  A: 

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.

Simon Nickerson
And you can do the split array part in-place, using the Dutch National Flag algorithm.
Moron
@Simon: Great solution. But now I realize that it only works fine when n is a power of 2. What about other numbers?
Eyal Schneider