Removing even/odd numbers in problem 5.7 of cracking the coding interview
Following is problem 5.7 (under Bit Manipulation) in the 5th edition of Cracking the coding interview:
An array A[1..n] contains all the integers from 0 to n except for one number which is missing. In this problem, we cannot access an entire integer in A with a single opera-tion. The elements of A are represented in binary, and the only operation we can use to access them is “fetch the jth bit of A[i]”, which takes constant time. Write code to find the missing integer. Can you do it in O(n) time?
The algorithm applied is this:
1. Start with LSB.
2. Count occurrence of 1's vs 0's.
If count(1) < count(0) it means the missing number has a 1 as it's LSB, else it has a 0.
3. Remove all numbers with LSB not matching result found in step 3.
4. Repeat steps 1 to 4, and progressively checking the next LSB in each iteration.
Can someone explain the logic behind step 3? It basically removes all odd/even numbers from the current list (depending on the bit found for the missing number) and uses the modified list in the next iteration. Why do we do this?
Open Chat in New Window