0:00 / 0:00

Find the two numbers that add up to the target. Walk once, and for each number look up the partner you need in a map of what you've seen.

▼

The problem

Given a list of numbers and a target, return the indices of the two numbers that add up to the target. There is exactly one answer, and the same element can't be used twice.

Example: nums = [5, 9, 2, 8, 3, 6], target = 12 → [1, 4] (9 + 3).

TRY IT ON LEETCODE ▶

The solution

def two_sum(nums, target):
    seen = {}                 # value -> index
    for i, x in enumerate(nums):
        need = target - x
        if need in seen:
            return [seen[need], i]
        seen[x] = i

Transcript

Two Sum. You get a list of numbers and a target. Find the two numbers that add up to the target, and return their positions. There's always exactly one answer, and you can't use the same element twice.

Here's our list: five, nine, two, eight, three, six, and the target is twelve. The obvious way is to try every pair. Five with nine, five with two, and so on, then nine with everything after it. Six numbers make fifteen pairs. That grows like n squared: a thousand numbers would mean about half a million checks.

So flip the question. When you're standing on a number, you already know its partner: the target minus that number. You don't need to search for it. You just need to remember. Keep a hash map from every number you've seen to its index. Asking the map whether a number is in it takes constant time, on average.

Now walk the list once. Five needs seven. The map is empty, so store five at index zero. Nine needs three. Not there yet, so store nine at one. Two needs ten: store it. Eight needs four: store it. Now three needs nine, and nine is in the map, at index one. The answer is one and four.

Notice the order: look first, then store. Our list ends with a six, and six needs six. If you stored it before looking, it would find itself. Looking first means the map only holds earlier numbers, so the partner is always a different element. With two sixes, the second would find the first.

In code, that's one loop and a dictionary. For each number, work out what it needs, check the map, and return if it's there. Otherwise, store it and move on. Each number is handled once, so it's linear time. The map can hold every number, so it's linear space too.

Don't search for the partner; remember who you've met. That's Two Sum.