views:

724

answers:

4

You are given 2^32-2 unique numbers that range from 1 to 2^32-1. It's impossible to fit all the numbers into memory (thus sorting is not an option). You are asked to find the missing number. What would be the best approach to this problem?

Edit: Let's assume you cannot use big-integers and are confined to 32bit ints.

ints are passed in through standard in.

+10  A: 

Add all the numbers you are given up using your favourite big integer library, and subtract that total from the sum of all the numbers from 1 to 2^32-1 as obtained from the sum of arithmetic progression formula

moonshadow
You don't even need a big integer library, `ulong` (an unsigned 64-bit integer) will do just fine.
Anton Tykhyy
You don't have to do either (64bits or arithmetic progression). Just count how many times each bit occurs, and you'll notice that sum==2^31 mod 2^32. Add all numbers, the missing one is 2^31-sum.
+1  A: 

Assuming you can get the Size() you can use some binary approach. Select the set of numbers n where n< 2^32 -2 / 2. then get a count. The missing side should report a lower count. Do the process iteratively then you will get the answer

Chathuranga Chandrasekara
+23  A: 

Major Edit: Trust me to make things much harder than they have to be.

XOR all of them.

I'm assuming here that the numbers are 1 to 2^32 - 1 inclusive. This should use 1 extra memory location of 32 bits.

EDIT: I thought I could get away with magic. Ah well.

Explanation:

For those who know how Hamming Codes work, it's the same idea.

Basically, for all numbers from 0 to 2^n - 1, there are exactly 2^(n - 1) 1s in each bit position of the number. Therefore xoring all those numbers should actually give 0. However, since one number is missing, that particular column will give one, because there's an odd number of ones in that bit position.

Note: Although I personally prefer the ** operator for exponentiation, I've changed mine to ^ because that's what the OP has used. Don't confuse ^ for xor.

sykora
Explanation please?
1800 INFORMATION
Question says from 1 to 2^32-1, so xoring all numbers is enough as it's said above.
Grzegorz Gierlik
Thanks @Grzegorz, I made it far more complicated than it had to be.
sykora
You can use <sup></sup> instead of ^ to remove all ambiguity.
Brian Campbell
+3  A: 

Use bitwise operator XOR. Here are example in JavaScript:

<html>
    <script>
    function run() {
     var d = new Array(6, 2, 4, 5, 7, 1);

     var r = 0;

     for (var i = 0; i < 6; i++) {
      r ^= d[i];
     }

     alert(r);
    }
    </script>

<body onload='run()'>
</body>
</html>
Grzegorz Gierlik