Amazon Interview Question
Software Engineer / Developers1 little optimization is possible
We need 2 numbers 1 <= 20/2 and 1 >= 20/2.
So we take the list and sort it.
Do a binary search on 20/2 = 10 (or more generically lower bound n/2)
and lets say you have ended up in location k (if k =0 or n-1) u can stright
away say you dont have any elements that sum up to 20
and have 2 pointers 1 running from 0->k and from k->n-1. summing up and checking
if equals 20
If there are no duplicates in the array.....create another array with elements as [20 - arr[i]]...merge these 2 arrays....if now the array has duplicates, it means there is a and b totalling to 20...
This is a very common question.
- algooz June 16, 2008k = a + b;
first approach:
Sort the array and take two pointers, one at the begining and one at end.
if((*p1 + *p2) < k){
++p1;
}
else if ((*p1+*p2) > k){
++p2;
}else{
print *p1 and *p2;
}
second approach.
Use Hash Table to store array elements and check if u can find a and b such that a+b = 20