Two Sum with a Hash Map

Find two numbers that add up to the target in one pass, by remembering what you have seen in a dictionary.

Python · intermediate · 6 min · 20 steps · free

What you'll learn

two_sum.py

def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        need = target - n
        if need in seen:
            return [seen[need], i]
        seen[n] = i
    return None

print(two_sum([3, 8, 5, 2], 7))

Step by step

  1. Python defines the function two_sum(). Its body does not run yet: it runs each time the function is called.
  2. Python calls two_sum(), with nums = [3, 8, 5, 2] and target = 7. It gets its own names.
  3. seen is created and points to a new dict: {}.
  4. i is created with the value 0. n is created with the value 3.
  5. To reach 7 from 3 we need 4.
  6. need in seen is false, so the block under it is skipped.
  7. Not seen yet: remember 3 at index 0.
  8. i changes from 0 to 1. n changes from 3 to 8.
  9. need changes from 4 to -1.
  10. need in seen is false, so the block under it is skipped.
  11. A new key 8 with the value 1 is added to the dict that seen points to.
  12. i changes from 1 to 2. n changes from 8 to 5.
  13. need changes from -1 to 2.
  14. need in seen is false, so the block under it is skipped.
  15. A new key 5 with the value 2 is added to the dict that seen points to.
  16. i changes from 2 to 3. n changes from 5 to 2.
  17. need changes from 2 to 5.
  18. We need 5, and seen has it, at index 2.
  19. The function returns [seen[need], i].
  20. two_sum() has finished, so its names are gone. It prints [2, 3].

Common mistakes

Best practices

Key takeaways

Check yourself

Brute force cost?

Answer: O(n²)

Extra memory used here?

Answer: O(n)

·

More in Lists, Stacks, Queues and Hashing