Solving the two sum algorithm

nums = [2,7,11,15] target = 9
var twoSum = function(nums, target) {
let output = {}
for(let i = 0; i < nums.length; i++){
}
nums = [2,7,11,15] target = 9var twoSum = function(nums, target) {
let output = {}
for(let i = 0; i < nums.length; i++){
const currentNum = nums[i]
const neededNum = target - currentNum
}
nums = [2,7,11,15] target = 9var twoSum = function(nums, target) {
let output = {}
for(let i = 0; i < nums.length; i++){
const currentNum = nums[i]
const neededNum = target - currentNum
//output = { 7:0, 7:2, -2:2, -6:3 }
nums = [2,7,11,15] target = 9var twoSum = function(nums, target) {
let output = {}
for(let i = 0; i < nums.length; i++){
const currentNum = nums[i]
const neededNum = target - currentNum
const value2 = output[neededNum]
if(value2 != null){
return [value2, i]
}else{
output[currentNum] = i
}
}
};

--

--

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