Amazon Interview Question
Software EngineersTeam: Seattle
Country: United States
Interview Type: Phone Interview
Looking for interview questions sharing and mentors? Visit A++ Coding Bootcamp at aonecode.com (select english at the top right corner).
We provide ONE TO ONE courses that cover everything in an interview from the latest interview questions, coding, algorithms, system design to mock interviews.
All classes are given by experienced engineers/interviewers from FB, Google and Uber. Help you close the gap between school and work. Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us with any questions.
If the array is sorted, simply run a binary search of log(n) time.
Otherwise, the best run time has to be linear.
Sum Solution (might get integer overflow):
1) Get the sum of all numbers n * (n + 1) / 2
2) Subtract all the numbers in array from sum and you will get the missing number.
int getMissingNo (int a[], int n)
{
int i, total;
total = (n+1)*(n+2)/2;
for ( i = 0; i< n; i++)
total -= a[i];
return total;
}
Bit Manipulation Solution:
1) XOR all the array elements, let the result of XOR be X1.
2) XOR all numbers from 1 to n, let XOR be X2.
3) XOR of X1 and X2 gives the missing number.
int getMissingNo(int a[], int n)
{
int i;
int x1 = a[0];
int x2 = 1;
for (i = 1; i< n; i++)
x1 = x1^a[i];
for ( i = 2; i <= n+1; i++)
x2 = x2^i;
return (x1^x2);
}
Assuming your sequence start at 1.
- Anonymous September 02, 2016int correct_sum = n*(n-1)/2;
int actual_sum = 0;
for (int i =1; i<=n;i++)
actual_sum += i;
int missing num = correct_sum - actual_sum
Time complexity: O(n) <- for the calculating the real sum.
If it does not start at 1 then might need some extra calculation.
i.e. sequence: 6,7,8,9
5+1, 5+2, 5+3,5+4 => 5*4 + (1+2+3+4) => 30.