2sum LeetCode Solution: JavaScript

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
var twoSum = function(nums, target) {
const previousNumbers = {};
}
var twoSum = function(nums, target) {
const previousNumbers = {};
for(let i = 0; i < nums.length; i++) {
const currentNumber = nums[i];
const numberNeeded = target - currentNumber
const index2 = previousNumbers[numberNeeded]
}
}
nums = [2,7,11,15] target = 9var twoSum = function(nums, target) {
const previousNumbers = {};
for(let i = 0; i < nums.length; i++) {
const currentNumber = nums[i];
const numberNeeded = target - currentNumber
const index2 = previousNumbers[numberNeeded]
if (index2 != null) {
return [index2, i]
} else {
previousNumbers[currentNumber] = i
}
}
}
currentNumber = 2;
numberNeeded = 7; (9 - 2 = 7)
index2 = previousNumbers[7] === null(does not exist yet)
*we will hit our else statement first iteration*
previousNumbers[2] = 0
previousNumbers = {
2:0
}
currentNumber = 7;
numberNeeded = 2; (9 - 7 = 2)
index2 = previousNumbers[2] = 0
*since index2 has a value this iteration our first condition is satisfied and we return a solution!*
return [index2, i] -- index2 = 0 and i = 1

previousNumbers = {
2:0
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store