Last active
October 23, 2020 12:13
-
-
Save d-beloved/b61785ccdecbc22358e9b9086ce373f2 to your computer and use it in GitHub Desktop.
A simple Three Number Sum Algorithm implementation
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
// using the pointer method the three number algorithm is solved | |
let threeSumArray = (array, targetSum) => { | |
array.sort((a, b) => a - b); | |
const triplet = [] | |
for (let i = 0; i < array.length - 2; i++) { | |
// initialize the pointers | |
let left = i + 1 | |
let right = array.length - 1 | |
while (left < right) { | |
let currentSum = array[i] + array[left] + array[right] | |
if(currentSum === targetSum) { | |
triplet.push([array[i], array[left], array[right]]) | |
left++ | |
right-- | |
} else if(currentSum < targetSum) { | |
left++ | |
} else { | |
right-- | |
} | |
} | |
} | |
return triplet | |
} | |
let arrays = [2, 1, 4, 3, 7, 5, 9, 6, 8, 15] | |
let targetSum = 18 | |
threeSumArray(arrays, targetSum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment