Trading memory for time: the two-sum idea
🌍 In real life. At a wedding you meet people one by one, and you want to know if someone here is from your own village. You could go back and ask every person you've already met, again and again. Or you could jot each village in a little notebook as you go: when a new person says their village, one glance at the notebook answers "have I met someone from there?".
The notebook costs a page of paper (memory) and saves you asking everyone again (time). That trade is one of the most useful ideas in algorithms.
The problem. Given a list nums and a target, find two different positions whose numbers add up to the target. This is two-sum, the same pair problem as Chapter 33 with positions instead of prices.
The idea in one sentence: as you walk the list, remember each number's position in a dict; for each new number x, the partner you need is target - x, and the dict says in O(1) whether you have already seen it.
Its words:
- complement: the partner a number needs,
target - x - seen: a dict from each number already passed to its position
- memory for time: the dict costs O(n) memory, but turns an O(n²) search into O(n)
How it works, step by step (nums = [3, 8, 5, 2], target 10):
- x = 3: need 7; not seen; remember {3: 0}
- x = 8: need 2; not seen; remember {3: 0, 8: 1}
- x = 5: need 5; not seen yet (only the 5 itself, which isn't stored yet); remember 5: 2
- x = 2: need 8; seen at position 1: the answer is (1, 3)
Why it is correct. Take the answer pair, positions i < j. When the walk reaches j, position i has already been stored, so target - nums[j] is found. And because each number is checked before it is stored, a number is never paired with itself.
What it costs, worked out. Two loops check n(n−1)/2 pairs; one pass with a dict does n lookups:
- n = 1,000: 499,500 pair checks against 1,000 lookups
- n = 100,000: about 5 billion against 100,000
The price is O(n) extra memory for the dict, against O(1) for the two loops. Watch the two shapes race (the chart plots n², about twice the number of pairs: Big-O keeps only the shape): O(n²) leaves the chart while O(n) climbs gently:
def two_sum(nums, target):
seen = {} # number -> its position
for j, x in enumerate(nums):
need = target - x
if need in seen: # O(1) on average
return seen[need], j
seen[x] = j # store AFTER checking
return None
print(two_sum([3, 8, 5, 2], 10))
print(two_sum([5, 1], 10)) # one 5 is not a pair
print(two_sum([5, 1, 5], 10))Mistakes and edge cases.
- storing x before checking pairs a number with itself:
[5, 1]with target 10 would wrongly answer (0, 0) - returning the numbers when positions were asked for, or the other way round
- with repeated numbers,
seen[x] = jkeeps the latest position; that is fine, because the earlier one was already checked - a set is enough when you only need whether a partner exists; a dict when you need where
Quiz
What does this print?
seen = {} for j, x in enumerate([4, 7, 1, 6]): if 11 - x in seen: print(seen[11 - x], j) break seen[x] = jWhat does the dict version of two-sum cost?
- O(n) time and O(n) extra memory
- O(n²) time and O(1) memory
- O(1) time and O(n) memory
With nums = [5, 1] and target 10 this answers (0, 0). Which line is in the wrong place?
def two_sum(nums, target): seen = {} for j, x in enumerate(nums): seen[x] = j if target - x in seen: return seen[target - x], j return NoneFor n = 1,000, how many pairs do two nested loops check? What does this print?
n = 1000 print(n * (n - 1) // 2)
Coding tasks
Write
two_sum(nums, target)in O(n): the positions(i, j), with i < j, of two numbers that add up totarget(the first such j as you walk the list), orNone.Write
count_pairs(nums, target)in one pass: how many pairs of positions i < j havenums[i] + nums[j] == target. Keep a dict of how many times each number has been seen so far.