Skip to content

Instantly share code, notes, and snippets.

@levymoreira
Created November 4, 2017 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save levymoreira/e3d5b5ed02a0b35c41ddea8e3680cb55 to your computer and use it in GitHub Desktop.
Save levymoreira/e3d5b5ed02a0b35c41ddea8e3680cb55 to your computer and use it in GitHub Desktop.
Given an array of integers, return the number of pairs whose sum is K
const _ = require('underscore');
class FindSum {
// O(n)
find(arr, totalSum) {
const m = new Map();
// O(n)
arr.forEach((value) => {
if (m.get(value) !== undefined) {
m.set(value, m.get(value) + 1);
} else {
m.set(value, 1);
}
})
let result = 0;
// O(n)
arr.forEach((value) => {
if (m.get(totalSum - value) !== undefined) {
result += m.get(totalSum - value);
}
if ((totalSum - value) === value) {
result--;
}
})
return result / 2;
}
}
const test = (currentResult, expectedResult) => {
if (!_.isEqual(currentResult, expectedResult)) {
console.log('Error!');
console.log('Current Result:');
console.log(currentResult);
console.log('Expected Result:');
console.log(expectedResult);
} else {
console.log('Success.');
}
}
var obj = new FindSum();
test(obj.find([9,1,3,11,8,7,5,5], 10), 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment