Skip to content

Two Sum

Lesson 2 of 8 · 5 min

Two Sum

Step 1 of 8

Checking every pair is O(n²). Instead, walk once and remember what has gone past.

The Idea

Comparing every pair costs O(n²). Instead, walk the list once and ask a map of seen values one question: has the complement — target minus this value — already gone past? A hash lookup answers instantly, so a single pass settles it.

Real-World Example

A hardware shop keeps a bin of timber offcuts, and a customer needs exactly 240 cm from two pieces. The clerk measures each offcut once, jotting lengths on a pad, and after every measurement glances at the pad for the missing remainder instead of re-searching the bin.

The Code

Your turn

Fill in the blank.

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

print(two_sum([90, 40, 200, 40], 240))   # want (1, 2)

Mini quiz

1 / 3

Time complexity of the hash-map two-sum?