Skip to content

Instantly share code, notes, and snippets.

@venil7
Created August 29, 2018 19:01
Show Gist options
  • Save venil7/0cfdb434f0a22a613928dc446bdbb3c3 to your computer and use it in GitHub Desktop.
Save venil7/0cfdb434f0a22a613928dc446bdbb3c3 to your computer and use it in GitHub Desktop.
pairs of array that sum to X, O(n)
let pairs = (arr: number[], s: number): number[][] => {
let cache = {};
let res = [];
for (let i of arr) {
if (!cache[i]) {
cache[i] = true;
}
let snd = s - i;
if (cache[snd]) {
res.push([i, snd]);
}
}
return res;
};
let res = pairs([1, 2, 4, 3, 0, 5, 9, 6, 8, 7].sort(), 7);
console.log(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment