LeetCode- Two Sum in Javascript
It is one of the most commonly asked problems in interviews. We can do this by various methods, like checking for pairs with respect to each value by using two loops, but we should opt for the optimal solution.
Here is the problem
Approach-
For an optimal solution, we will use a map or simply an object to store all values through which we will loop, and the idea is to check whether the opponent number (target-current number) is present in our object; if so, then we have our needed pair.
Solution -
var twoSum = function(nums, target) {
let freq={}
for(let i=0;i<nums.length;i++){
let opp=target-nums[i]
if(freq[opp]!== undefined){
return [i,freq[opp]]
}
freq[nums[i]]=i
}
};
Explanation-
for example 1:
when i = 0 => nums[i] = 2.We check opp (9–2 = 7) whether 7 is present in frequency or not by this condition; if it is not, then we store the current number in the object and its index as value.
We used undefined instead of 0 because 0 is also false.
then when i = 1 and nums[i] = 7, its opponent 9–7 = 2 is present in the object, so we return the value of the opponent index that we stored in the object and the current index in the array as required.
I hope it helps if you get stuck.👍👍👍
Try it on your own once after going through the solution.