Saturday, February 2, 2013

Finding a duplicate number in an array of random numbers?

Suppose you have an array of 1001 integers. The integers are in random order, but you know each of the integers is between 1 and 1000 (inclusive). In addition, each number appears only once in the array, except for one number, which occurs twice. Assume that you can access each element of the array only once. Describe an algorithm to find the repeated number. If you used auxiliary storage in your algorithm, can you find an algorithm that does not require it?



Answer:


The solution here is straight forward. Sum all the numbers and subtract (1000*1001)/2 from that. The result is the no you are looking for.

Eg:
Input: 1,2,3,2,4 => 12
Expected: 1,2,3,4 => 10
Input - Expected => 2

No comments:

Post a Comment