Given an array of n+1
integers, each in the range 1
to n
, find an integer that is repeated.
I was asked this at a job intervi
If you know that there is exactly one number that is duplicate you can find it by summing all of them and subtracting the sum of numbers from 1 to n:
duplicate = sum P[i] - n(n+1)/2
If not, then you can iterate through the array and put each number in a hashtable. If the number already exists then that's the duplicate. This is also O(n) assuming the hashtable operations are O(1).
Or event better - to avoid the hashtable you can use an array of booleans of size n:
int[] P = new int[] { 3, 2, 5, 1, 4, 2 };
bool[] Q = new bool[6];
foreach( var p in P ){
if ( Q[p] ) {
Console.WriteLine("Duplicate: " + p);
break;
}
Q[p] = true;
}