Possible Duplicate:
Quickest way to find missing number in an array of numbers
Input: unsorted array A[1,..,n] which contains all but one of the integers in the range 0,..,n
The problem is to determine the missing integer in O(n) time. Each element of A is
represented in binary, and the only operation available is the function bit(i, j), which
returns the value of the jth bit of A[i] and takes constant time.
Any ideas? I think some sort of divide-and-conquer algorithm would be proper, but I can’t think of what exactly I should do. Thanks in advance!
It’s a mathematical property that the sum of the numbers between
1andnwherenisn(n+1)/2. You can see this for10:So, by extension, is the sum of the numbers from
0thrunsince you’re just adding 0 to it. So what you do is add up all the numbers and maintain a count, then use that formula to figure out the missing one.So, something like:
Getting the number with
bit(i,j)is tricky so you’ll have to extract the bits individually and turn them into actual numbers for summing.