Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Created June 17, 2018 23:11
Show Gist options
  • Save pinkmomo027/4c4a414beb8edb1004f2d1651280aea4 to your computer and use it in GitHub Desktop.
Save pinkmomo027/4c4a414beb8edb1004f2d1651280aea4 to your computer and use it in GitHub Desktop.
find triplets summing to 0
const arr = [0, -1, 2, -3, 1];
// [ -3, -1, 0, 1, 2 ]
function triplets(arr) {
let sorted = arr.sort((a, b) => { return a > b; });
let answer = [];
for(p1 = 0; p1 < sorted.length - 2; p1++) {
let target = -sorted[p1];
p2 = p1 + 1;
p3 = sorted.length - 1;
while(p2 < p3) {
if((sorted[p2] + sorted[p3]) > target) {
p3--;
} else if ((sorted[p2] + sorted[p3]) < target) {
p2++;
} else {
let found = [sorted[p1], sorted[p2], sorted[p3]];
answer.push(found);
p2++;
p3--;
}
}
}
return answer;
}
console.log(triplets(arr));
console.log(triplets([1, -2, 1, 0, 5]));
@pinkmomo027
Copy link
Author

[ [ -3, 1, 2 ], [ -1, 0, 1 ] ]
[ [ -2, 1, 1 ] ]
[Finished in 0.1s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment