Skip to content

Instantly share code, notes, and snippets.

@d-beloved
Last active October 23, 2020 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-beloved/b61785ccdecbc22358e9b9086ce373f2 to your computer and use it in GitHub Desktop.
Save d-beloved/b61785ccdecbc22358e9b9086ce373f2 to your computer and use it in GitHub Desktop.
A simple Three Number Sum Algorithm implementation
// 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