0

Example 1:

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

const twoSum = function(nums, target) {
  const map = {}
  for (let i=0; i<nums.length;i++) {
    if (map[target-nums[i]] !==undefined ) return [map[target-nums[i]],i]
    else map[nums[i]] = i
  }
}

Now my question is...

if (map[target-nums[i]] !==undefined ) return [map[target-nums[i]],i]

From the code above, when i first coded this, i wrote:

if (map[target-nums[i]]) return [map[target-nums[i]],i]. (without !==undefined)

Thinking that if i have the pair in the hashmap, it would work, but it did not work, and when i looked up the answer, i realized i had to write !==undefined. Why are these considered different?

Abhinav Mathur
  • 7,791
  • 3
  • 10
  • 24
David L
  • 77
  • 1
  • 9

0 Answers0