Skip to content

Instantly share code, notes, and snippets.

@tdubs42
Last active February 19, 2024 01:32
Show Gist options
  • Save tdubs42/12ae2bf3e58ea814aefb39afe4737e22 to your computer and use it in GitHub Desktop.
Save tdubs42/12ae2bf3e58ea814aefb39afe4737e22 to your computer and use it in GitHub Desktop.
Two Sum - JavaScript
const twoSum = (nums, target) => {
// given an array, return pair of indices corresponding to numbers in array that equal target
// there is exactly 1 solution per array of nums
// need variable to store indices of solution
const solution = []
// need variable to store count to leverage while loop
let count = 0
// create while loop to be able to iterate through entire nums for each num
while (count < nums.length) {
// need to iterate through nums and add nums[count] + num
nums.forEach((num, index) => {
// check if index < count, if so, do not calculate
if (nums[count] + num === target && index > count) {
solution.push(count)
solution.push(index)
console.log(count, index)
}
})
// need to increase count to continue loop
count ++
}
// return solution array with indices
return solution
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment