Created
February 16, 2021 06:27
-
-
Save MohammedALREAI/ed6d27014dbace5870328a08ff62f9f8 to your computer and use it in GitHub Desktop.
threeNumberSum AlgoExpo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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