Amazon Interview Question
Software Engineer / DevelopersSort array A of n numbers
Keep one pointer p at n/2 number
Keep second pointer q at n/2+1 number
Take sum of the two numbers S = A[p]+A[q]
while(p>=0 and q<n)
{
if(A[p]==A[q])
return true
while(S>N&&p>0)//N is required sum
{
p--;
S=A[p]+A[q];
}
while(S<N&&q<n-1)
{
q++;
S=A[p]+A[q];
}
}
return false;
End
1). Sort the array. (NlogN)
2). For each number x, find s-x using binery search. (N*logN).
Not any better. But an alternative.
sort the array(O(nlogn))
keep two index variables one at each end of the sorted array
if the sum of values at the two indices is less than given value increment left variable ;else if it is greater than given value decrement the right variable; else,
we have found the variables.
continue this until the two index variables cross in which case no two integers sum up to given value.
use hash table,
- Anonymous August 27, 2008in linear time.