1

I am solving the following leetcode question and have the solution below

const twoSum = (numbers, target) => {
    let map = {}
    let result = []
    for (let i = 0; i < numbers.length; i++) {
        let complement = target - numbers[i]
        if (map[complement] === undefined) {
            map[numbers[i]] = i
        } else {
            result[0] = map[complement] + 1
            result[1] = i + 1
        }
    }
    return result
};

If I replace map[complement] === undefined with !map[complement] I return an empty array. In my mind both should return true. Why does the latter breaks my code?

dev_el
  • 2,357
  • 5
  • 24
  • 55
  • 2
    Does `map[complement]` produce a zero at any point? [All falsey values in JavaScript](https://stackoverflow.com/q/19839952) – VLAZ Dec 23 '21 at 12:09
  • @VLAZ It certainly does. The constraint is [-1000, 1000]. – zhulien Dec 23 '21 at 12:12
  • This also might help clarify some things: [Leetcode Two sum problem question about why my code doesn't work](https://stackoverflow.com/q/59674537/5648954) – Nick Parsons Dec 23 '21 at 12:13
  • _"I am solving the following leetcode question..."_ - Please add the relevant parts of the question _in_ your question here. If the leetcode site dies your question should still be complete and reproducible. – Andreas Dec 23 '21 at 12:14
  • 1
    @Andreas to be honest, it's probably irrelevant for a [mcve] - if it boils down to just truthy/falsy, then it should just be asking "why `if (!obj[x] === undefined)` doesn't behave the same as `if (!obj[x])` when `obj[x]` is `0`" or something along those lines. We don't need the whole algorithm and the problem it's solving if it's just literally that one line that's relevant. – VLAZ Dec 23 '21 at 12:17

1 Answers1

0

map[complement] === undefined only becomes true when there is no element with the key equal to complement while !map[complement] becomes true in all the cases where its result is a falsy value.

Falsy values include but are not limited to, "", false, undefined, null, 0, -0, etc.

In other words, the first case is a sub set of the second.

adiga
  • 34,372
  • 9
  • 61
  • 83
user1984
  • 5,990
  • 2
  • 13
  • 32