An array a[] contains all of the integers from 0 to N, except one. However, you cannot access an element with a single operation. Instead, you can call get(i, k) which returns the kth bit of a[i] or you can call swap(i, j) which swaps the ith and jth elements of a[]. Design a O(N) algorithm to find the missing integer.
(For simplicity, assume N is a power of 2.)
An array a[] contains all of the integers from 0 to N, except one.
Share
If N is a power of 2, it can be done in
O(N)using divide and conquer.Note that there are
logNbits in the numbers. Now, using this information – you can use a combination of partition based selection algorithm and radix-sort.halves – the first half has this bit as 0, the other half has it as 1. (Use the
swap()for partitioning the array).ceil(N/2)elements, and the other hasfloor(N/2)elements.number.
The complexity of this approach will be
N + N/2 + N/4 + ... + 1 < 2N, so it isO(n)