Leetcode: Two Sum (JS)

Tish Faroul
2 min readJun 24, 2022

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Understanding the problem:

Per the example above, if we start with 2, and we want to reach 9 — we need to add 7 from the array. The indices for 2 and 7 are 0 and 1.

How do we do this?

function twoSum(nums, target){// a map that holds the numbers and their indices
let numberIndex = new Map();
// we need an array for our indices results
let result = [];
// loop through the nums array
for (let i=0; i < nums.length; i++){
//current element we're on
let currentNum = nums[i];
// save the difference between the number we're on and the target
let neededNum = target - currentNum;
// check to see if the map has the number we need
if (numberIndex.has(neededNum)){
result[0] = numberIndex.get(neededNum);
result[1] = i;
return result;
}
//if they don't match, add the current number & index to the map
numberIndex.set(currentNum, i)
}
// return our indices results
return result;}

Another Solution:

function twoSum(nums, target){// a map that holds the numbers and their indiceslet map = new Map();
// loop through the nums array
for (let i = 0; i < nums.length; i++){
//current element we're on
let currentNum = nums[i];
// save the difference between the number we're on and the target
let neededNum = target — currentNum;
// check to see if the map has the number we need
if (map.has(neededNum)){
// return our indices results
return [i, map.get(neededNum)];
}
//if they don't match, add the current number & index to the map
map.set(currentNum, i);
}

✨✨✨And that’s it!

Tish⚡️🎧🌙

--

--