This week's book giveaway is in the Jobs Discussion forum.We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Java Interview Guide this week in the Jobs Discussion forum!

# Finding which two numbers are missing from a bag

Aneek Banerjee
Ranch Hand

Joined: Jun 20, 2012
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

Joined: Jan 06, 2009
Posts: 181
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

Joined: Mar 12, 2011
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

Joined: Jan 28, 2008
Posts: 5575

https://www.google.com/search?q=how%20to%20find%202%20missing%20numbers%20in%20an%20array . very first url sounds Ok.
Praveen Kumar M K
Ranch Hand

Joined: Jul 03, 2011
Posts: 256