DEV Community

Discussion on: The Two Sum Problem in JavaScript

Collapse
 
muhammedyousrii profile image
Muhammed Yousrii

Bravo, so simple and powerful,

The result of the previous example will be [1, 2, 2, 1]
So we need an solution for it,

We can break the array once the goal is achieved, Or to union the returned array using following expression

return [... new Set(...twoIndexes)]

another thing along side the above improvment which can improve performance of your solution is like you know JS return false for falsy values and 0 considered falsy value even it's a real value like 0

So we need to replace the first part of the IF condition to be
mapOfNumbers[target] != null Instead of mapOfNumbers[target]

Because what if index of the target is 0 ? it will return false
so we continue looping through the array for no reason

Collapse
 
eidorianavi profile image
EidorianAvi

Great catch and a super good point! I'm going to edit that into the post much appreciation.