Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Finding which two numbers are missing from a bag

Aneek Banerjee
Ranch Hand
Posts: 61
There are total 50 integer nos in a bag.Starting from 1 to 50.Now lets say two random numbers are missing from the bag.
How I can find which two nos are missing.

I can solve the problem for any random single no is missing.But struck when it asked what are the two random numbers are missing..

Any idea how to do that.

Kevin Florish
Ranch Hand
Posts: 182
Well one way I can think of off the top of my head is to put the remaining numbers into an array.
Sort the array and then do a for loop (1 48) and when the increment doesn't match a number in the array (-1) you have your first number, if you don't get a mismatch then the numbers are 49 and 50.
Then reverse the array and do a for loop from 50 backwards checking against index 0, 49 against index 1 etc.
When you get a mismatch you have your second number, or if you hit index 47 and no mismatch the second missing number is 2.
...
Another way could be to make an array of size 51 and put each remaining number into array slot number +1.
Then check array and the array entries between 1 and 50 that have no values are your missing numbers.

I am sure their are more elegant solutions but I think these will work.

dennis deems
Ranch Hand
Posts: 808
Kevin Florish wrote:Another way could be to make an array of size 51 and put each remaining number into array slot number +1.
Then check array and the array entries between 1 and 50 that have no values are your missing numbers.

You wouldn't even need to store the numbers. Just make it a boolean array and for each number encountered set the value of array[number] to true.

Seetharaman Venkatasamy
Ranch Hand
Posts: 5575

Praveen Kumar M K
Ranch Hand
Posts: 256