Problem-Solving(TWO SUM)

Two Number Sum

Anil Verma's photo
Anil Verma
ยทFeb 18, 2022ยท

Subscribe to my newsletter and never miss my upcoming articles

Play this article

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

Input: nums = [2,7,11,15], target = 9
Output: [0,1]

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

Solution 1(Good)

const twoSum = function (nums, target) {
let temMap = {};
if (nums?.length < 2) {
return null;
}
for (let i = 0; i < nums.length; i++) {
const index = target โ€” nums[i];
if (temMap[index] !=null ) {
return [temMap[index],i]
}
if (!temMap[nums[i]]) {
temMap[nums[i]] = i;
}
}
return null;
};

Solution 2(Just Ok)

const twoSum = function (nums, target) {
if(nums?.length <2){
return null
}
else{
for(let i=0; i<=nums.length; i++){
for(let j= i+1; j<=nums.length; j++){
if(nums[i] + nums[j] ===target){
return [i, j]
}
}
}
}
return null
};

Happy Learning โ€ฆ.๐Ÿ‘๐Ÿ‘๐Ÿ‘

ย 
Share this