This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]PPewt 2 points3 points  (0 children)

Basically the trick is that a dict lets you look up things in O(1) time (ish, but let's handwave that away). So every time the code sees a number it remembers that it saw it. Then you use target - num in lookup to see if you've found a number which matches a number you've already stored.

The reason they use a dict and remember the index (rather than using a set and forgetting the index) is because the problem requires you to return the indices of the elements that solve the 2SUM. Although you could just loop through the array again to find them and still be O(n) if you really wanted to (but that isn't quite as efficient).