Amazon Interview Question
Software Engineer / DevelopersCan someone explain this ? How this works ?
>>>> 2. Uisng sorting as a preprocessing step and binary search. ie. O(nlogn).
We sort the array first O(n)
For each integer, we do binary search for sum-integer in the remaining array, which requires O(log(n))
Therefore, the total is O(nlog(n)).
accu rp
It should be able to handle negative numbers just fine.
Some pseudocode..
Let the number we're trying to sum upto be SUM
Step 1.
foreach(int n in array)
{
int complement = SUM - n;
if(hashTable.containsKey(complement)
return true; // found the pair {n, complement}
hashTable.Add(n, complement);
// You can simply choose to add true or 1 here. I chose to add the complement value as the
// value part of the key,value pair thing.
}
Step2. There is no step 2.
It should work wiht -ve numbers just fine
for example
a = [2, -2, 5, 6, 9, -14, -3]
sum = 3
hashtable[-2] = 5
so -2, and 5 will be a valid pair
Why hashing method can not handle negative numbers?
- Hrishikesh May 13, 2010