Possible Duplicate:
Easy interview question got harder: given numbers 1..100, find the missing number(s)
A job interview question. Suppose we have an array of size N-2, with all the values from 1 to N, except for two missing values. (N>0)
An algorithm for finding the two missing numbers is needed, that traverses the array only once.
asked Dec 16, 2012 at 16:10
1 Answer 1
// Receiving array with values from 1 to N (NOT 0 to N-1)
// N is max value & # of values, NOT size of arr (arr is in size N-2)
void Find2Numbers(unsigned arr[], size_t N, unsigned & n1, unsigned & n2)
{
unsigned sum = N*(N+1)/2; // sum of elements
double pro = 1; // Products will be calculated within the loop, because fact(N) can be very large
for(size_t i = 0 ; i < N-2 ; i++)
{
pro *= (i+1); // mult by i+1 to get factorial
pro /= arr[i]; // divide by arr[i] to find n1*n2
sum -= arr[i];
}
pro *= (N-1)*N; // 2 missing indexes, as arr is missing 2 elements
// sum = n1+n2
// pro = n1*n2 =>
n1 = (sum+sqrt(sum*sum-4*pro))/2;
n2 = (sum-sqrt(sum*sum-4*pro))/2;
}
answered Dec 16, 2012 at 16:10
-
@NPE - you multiply and then you immediately divide.Leonid Volnitsky– Leonid Volnitsky2012年12月16日 16:24:56 +00:00Commented Dec 16, 2012 at 16:24
-
@NPE - I've ran it for N=10,000 and it works just fine. I would have checked it for 100,000 but sum=N*(N+1) overflows, so you can take the code and change it to calculate sum within the loop as well to see if works for a very large N.StackHeapCollision– StackHeapCollision2012年12月16日 16:25:30 +00:00Commented Dec 16, 2012 at 16:25
-
@LeonidVolnitsky: Oh, I missed the division. Question withdrawn.NPE– NPE2012年12月16日 16:26:36 +00:00Commented Dec 16, 2012 at 16:26
lang-cpp