Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

two sum problem always returns empty array

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));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading