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));
3
Answers
The code you provided for the twoSum function is almost correct, but there is a small mistake in it. Instead of storing the indices of the elements in the map object, you need to store the indices of the complement elements (comp) in the map object. Here’s the corrected version of the code:
In the corrected code, the map object is used to store the indices of the complement elements (comp) rather than the original elements. When a complement element is found in the map, it means that the current element and the complement element add up to the target value. In that case, the indices stored in the map and the current index i are returned as the result.
Running the corrected code will output [0, 1], which indicates that the elements at indices 0 and 1 (2 and 7) in the input array add up to the target value of 9.
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:
Please take a look below: