Leetcode: Two Sum (JS)

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⚡️🎧🌙

--

--

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
Tish Faroul

Tish Faroul

7 Followers

MHA grad & Software Engineer | Rails | React | JavaScript | CSS | HTML