# Is there any more efficient way to code this “2 Sum” Questions JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

Our job is to write a function that solves the two-sum problem in at most linear time.

## Two Sum Problem

Given an array of integers, we have to find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers that add up to the target, and if no two elements add up to the target, our function should return an empty array.

## Solving the problem in O(n) time

We will use a hashmap to keep a record of the items already appeared, on each pass we will check whether there exists any element in the map which when added to the current element add up to the target, if there are any we will return an array containing their indices and if we go through the whole loop without satisfying this condition, we will return an empty array.

## Example

const arr = [2, 5, 7, 8, 1, 3, 6, 9, 4];
const sum = 10;
const twoSum = (arr, sum) => {
const map = {};
for(let i = 0; i < arr.length; i++){
const el = sum - arr[i];
if(map[el]){
return [map[el], i];
};
map[arr[i]] = i;
};
return [];
};
console.log(twoSum(arr, sum));
console.log(twoSum(arr, 12));
console.log(twoSum(arr, 13));
console.log(twoSum(arr, 14));
console.log(twoSum(arr, 24));

## Output

The output in the console will be −

[ 2, 5 ]
[ 1, 2 ]
[ 1, 3 ]
[ 3, 6 ]
[]