Missing number in a sequence problem

I was recently given a problem to find a missing number in a sequence of numbers from 1..100 in the quickest way possible. The problem suggested that I have some java code that receives the stream of integers from 1 to 100 in a random order, however with one number missing (we make some assumptions here that I know when the stream is finished).

1.  The most obvious solution would be to sort the numbers ascending, then count from 1..100 until we find the missing one. But this can be very slow for larger ranges i.e. 10 million.

2.  Another solution is to sort the numbers ascending and then add the numbers at opposite ends working your way to the middle i.e 1+100, 2+99, 3+98, 4+97  which in each case add upto 101 each time. This way we only loop through half the sequence, with one loop starting at the beginning and the other one from the end. Then, if we suddenly get a result=100, then we know we have just skipped a higher number, and likewise if the result=102, then we have just skipped a lower number.

3. The third solution I came across is to realise that the sequence of numbers is a simple arithmetic progression. We can work out the sum simply by N(N+1)/2  where N represents the number of elements. So we can get the expected sum without any form of looping, and also we have the actual sum of the numbers which we can easily work out by adding the numbers up as they are streamed in. Simple subtraction of the 2 sums gives us the missing number.

Leave a comment