# 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];let neededNum = target - currentNum;// save the difference between the number we're on and the target

if (numberIndex.has(neededNum)){

// check to see if the map has the number we need

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 result;}

// return our indices results

Another Solution:

function twoSum(nums, target){let map = new Map();// a map that holds the numbers and their indices

for (let i = 0; i < nums.length; i++){// loop through the nums array

let currentNum = nums[i];//current element we're onlet neededNum = target — currentNum;// save the difference between the number we're on and the target

if (map.has(neededNum)){// check to see if the map has the number we needreturn [i, map.get(neededNum)];// return our indices results

}map.set(currentNum, i);//if they don't match, add the current number & index to the map

}

✨✨✨And that’s it!

Tish⚡️🎧🌙