Algorithms · Hash maps
Two Sum
Find the two numbers that add up to a target.
The problem
Return the positions of the two numbers in nums that add up to target, smaller position first. There is always exactly one answer, and you can’t use the same position twice.
two_sum([2, 7, 11, 15], 9)→[0, 1]two_sum([3, 2, 4], 6)→[1, 2]Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def two_sum(nums, target):take the numbers and the target for i in range(len(nums)):pick a first number for j in range(i + 1, len(nums)):try every number after it if nums[i] + nums[j] == target:do they add up? return [i, j]hand back both positionsNow ask: what if there were a billion?
When one dictionary can’t hold everything, companies split it across many machines by hashing the key. Discord uses a hash ring so that adding a machine only moves a few keys.
Aim for O(n)🧩 classic
Think it through
You’re looking at the number 7 and the target is 9. What do you know?
- Nothing yet
- Its partner must be exactly 2
Show the answer
Its partner must be exactly 2. Each number tells you exactly which partner it needs: target - x. So the question becomes “have I seen that partner?”, which is a lookup, not a search.
What should you remember about each number you pass?
- Just the number
- The number and where it was
Show the answer
The number and where it was. The answer is positions, so store number → position in a dictionary. Then finding a partner is one step instead of a walk through the whole list.
Stuck? 3 nudges, smallest first
- For each number
x, you know exactly which partner it needs:target - x. - Instead of searching for the partner every time, remember every number you’ve passed in a dictionary: number → position.
- For each
i, x:need = target - x. Ifneed in where, return[where[need], i]. Otherwise storewhere[x] = i.
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def two_sum(nums, target):take the numbers and the target where = {}number → the position we saw it at for i, x in enumerate(nums):look at each number once, with its position need = target - xthe partner this number needs if need in where:have we already seen that partner? return [where[need], i]yes: the partner's position, then ours where[x] = iremember where this number livesWhere it’s used for real
Solve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.