It always returns empty array.
Implement solution to two sum problem in javascript
function twoSum(nums, target) {
const map = {};
for (let i = 0; i < nums.length; i++) {
let comp = target - nums[i];
if (map[comp] !== undefined) {
return [map[comp], i];
} else {
map[comp] = i;
}
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9));
>Solution :
Your function logic is correct but there seems to be a small mistake. Instead of storing the complement of the number (comp) in the map, you should store the actual number in the map.
Here’s the corrected solution:
function twoSum(nums, target) {
const map = {};
for (let i = 0; i < nums.length; i++) {
let comp = target - nums[i];
if (map[comp] !== undefined) {
return [map[comp], i];
} else {
map[nums[i]] = i; // Store the actual number, not its complement.
}
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9)); // Should return [0, 1]