Skip to content

Instantly share code, notes, and snippets.

@MohammedALREAI
Created February 16, 2021 06:27
Show Gist options
  • Save MohammedALREAI/ed6d27014dbace5870328a08ff62f9f8 to your computer and use it in GitHub Desktop.
Save MohammedALREAI/ed6d27014dbace5870328a08ff62f9f8 to your computer and use it in GitHub Desktop.
threeNumberSum AlgoExpo
function threeNumberSum(array:Array<number>, targetSum:number):Array<Array<number>> {
array= array.sort((a, b) => a - b);
const triplets = [];
for (let i = 0; i < array.length - 2; i++) {
let left = i + 1;
let right = array.length - 1;
while (left < right) {
const currentSum = array[i] + array[left] + array[right];
if (currentSum === targetSum) {
triplets.push([array[i], array[left], array[right]]);
left++;
right--;
} else if (currentSum < targetSum) {
left++;
} else if (currentSum > targetSum) {
right--;
}
}
}
return triplets;
}
console.log(threeNumberSum([12,3,1,2,-6,5,-8,6],0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment