## Groupon Interview Question

Software Engineer / Developers**Country:**United States

**Interview Type:**Phone Interview

If I understand the problem statement correctly, hashes seem like overkill. The parameters of the problem are merely to give the pairs of numbers which equate to a sum - I see no indication that limits the operands to a given set. In this forum, I will make the assumption that results should not include duplicates (e.g. when sum is 4, only return one of 1,3 and 3,1. If I were in an interview, I would ask for clarification. That said, here's a C++ option:

```
#include <list>
#include <utility> // pair
std::list< std::pair<int,int> > getNumberPairsForSum(int sum)
{
std::list< std::pair<int,int> > result;
int a = 0;
int b = sum;
while(a <= b)
{
result.push_back(std::make_pair(a++,b--));
}
return result;
}
```

The solution is HashMap based, O(n)... Say given no is n. At each step, say current no is a, see if :

a. a is present in hashset. If it is present, then print a, n-a.

b. If it is not present save n-a into the hashset.

If you can use O(nlogn) solution sort the array and traverse from left and right. At each step:

a. If the sum is less than n then increment left index.

b. If the sum is greater increment right index.

c. If the sum is equal to n, print the two nos. And decrement left.

f. Repeat the above process. Stop when left > right.

Here is two solution - iterative and hashtable in javascript

```
var min = 1,
max = 100,
i,
arr = [];
for (i = min; i < max; i++)
{
arr.push(i);
}
//Yes I know it is already sorted - it just indicate that fact that sorting is required
arr.sort(function(a, b) {
return a - b;
});
function isPairSumIterative(arr, k) {
var start = 0,
end = arr.length - 1;
while (start < end) {
var sum = arr[start] + arr[end];
if (sum === k) {
return true;
} else if (sum > k) {
end--;
} else {
start++;
}
}
return false;
}
function isPairSumHashTable(arr, k) {
var hash = {}, found = false;
arr.some(function(item){
var diff = k - item;
if (diff >= 0 && hash[diff]) {
found = true;
return true;
} else {
hash[item] = 0;
}
});
return found || hash[k] !== undefined;
}
console.log(isPairSumIterative(arr, 92));
console.log(isPairSumHashTable(arr, 92));
```

using hashmap will give o(n) solution

- Amit July 18, 2013otherwise you can sort and search to get o(nlogn) time complexity

naive search will give o(n^2) time complexity