Two Sum Problem (JavaScript)

Oğuzhan Bilgin
2 min readApr 9, 2022

The Two Sum problem states that given an array of integers, return indices of the two numbers such that they add up to a specific target. We can’t use the same element twice.

Example 1:

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

Example 2:

Input: nums = [3,3], target = 6
Output: [0,1]

We’ll start getting into solutions below.

var twoSum = function(nums, target) {
let map = new Map();
for(let i=0; i<nums.length; i++){
let num1 = nums[i];
let num2 = target-num1;
if(map.has(num2)){
return[i, map.get(num2)];
}
map.set(num1,i);
}
};

In this example we declare an empty Map and then loop through the array of numbers. For each number, we check if the required complement exists in the Map, returning both numbers if so, or we add the current number into the Map. By the time the loop has reached the end of the array, we then have a map of all values provided

Maps are incredibly quick for looking up data, so this solution is much faster than the nested for loop approach, but surprisingly it’s not the most common solution I see to this type of answer.

Here we are:

Runtime Performance
Memory Performance

Thanks for reading!

--

--