Sonu Kumar
2 min readMay 29, 2024

Two Sum Problem in JavaScript

two sum problem using javascript

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

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,2,4], target = 6
Output: [1,2]

Example 3:

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

I am going to fix this problem using javascript.
Solutions 1:
This is brute force approach we can achieve our result but it took more time.
Time complexity: O(n2) Quadratic

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i; j < nums.length; j++) {
if (nums[i]+nums[j+1] === target) {
return [i, j+1]
}
}
}
};

console.log(twoSum([2,7,11,15], 9))

// Example 1
let nums = [2, 7, 11, 15];
let target = 9;
console.log(twoSum(nums, target)); // Output: [0, 1]

// Example 2
nums = [3, 2, 4];
target = 6;
console.log(twoSum(nums, target)); // Output: [1, 2]

// Example 3
nums = [3, 3];
target = 6;
console.log(twoSum(nums, target)); // Output: [0, 1]

Solution 2: Faster than 1
Time Complexity: O(n) Linear

const twoSum = function (nums, target) {
const numToIndex = new Map();

for (let i = 0; i < nums.length; i++) {
const num = nums[i];
const complement = target - num;

if (numToIndex.has(complement)) {
return [numToIndex.get(complement), i];
}

numToIndex.set(num, i);
}

return [];
}

// Example 1
let nums = [2, 7, 11, 15];
let target = 9;
console.log(twoSum(nums, target)); // Output: [0, 1]

// Example 2
nums = [3, 2, 4];
target = 6;
console.log(twoSum(nums, target)); // Output: [1, 2]

// Example 3
nums = [3, 3];
target = 6;
console.log(twoSum(nums, target)); // Output: [0, 1]

There are many more approach to solve this but this two are my Favorit way.

For learning the data structure and algorithm using javascript please follow me.

#datastructure #javascript #competiveprograming

Sonu Kumar

Full stack Web developer with experience and I love reading article such blogs books and writing.