Find all groups of three values from an array that add up to the given value
const threeSum = (arr, sum) => {
const ans = [];
const ilength = arr.length-2;
const jlength = ilength+1;
let check = false;
for(let i=0, j=i+1, k=j+1; i<ilength; i++, j++, k++) {
if (arr[i]+arr[j]+arr[k] === sum) {
ans.push([arr[i], arr[j], arr[k]]);
}
if (j<jlength) {
i--;
} else {
j=i+1;
}
if (k<arr.length) {
j--;
} else {
k=j+1;
}
}
return ans;
}
Test Input
console.log(threeSum([-1, 0, 1, 2, -1, -4, -3, 5, -6, 0], 4))
Output
[ [ -1, 0, 5 ],
[ -1, 5, 0 ],
[ 0, -1, 5 ],
[ 2, -3, 5 ],
[ -1, 5, 0 ] ]
Run the code here:
https://repl.it/@VinitKhandelwal/15-leetcode-3sum
Comments
Post a Comment