Skip to the workspace
Pebellslearn by building
Arrays & Hashing  ›  Lesson

Complement Lookup: Finding a Pair That Adds Up

Two Sum 12 minTo find two values that add up to a target, walk the list once and look up each value's complement, the target minus the value, in a dictionary of values already seen.

leetcode / Complement Lookup: Finding a Pair That Adds Up

Explore each scene at your own pace.

01 · The rule

The rule

Complement Lookup: Finding a Pair That Adds Up

You have a gift card worth exactly 50 and a shelf of items with prices. You want two different items that use the card up exactly, and you need to say which two. Trying every pair works, but on a big shelf it is painfully slow. The trick is to stop asking "which pairs add up?" and start asking "what does this item still need?"

The rule

For each value, look up what it still needs: target minus value.

If an item costs 12 and the card is worth 50, its partner must cost exactly 38. That number, 38, is its complement. So walk the shelf once, and for each price check whether its complement has already gone past. A dictionary remembers every price you have passed, together with where it was:

def pair_for(prices, target):
    where = {}                          # price -> position
    for i, price in enumerate(prices):
        need = target - price
        if need in where:               # has the partner gone past?
            return (where[need], i)
        where[price] = i                # remember this one for later
    return None

It is the seen-set from the last lesson with two upgrades: you look up the complement instead of the item itself, and a dictionary stores the position because the answer asks for it. One pass, n steps, and memory for up to n prices.

The idea stretches to any rule where the partner can be worked out from the value alone, such as a pair with a given difference, which the exercise at the end explores. And if the prices were already sorted, the two-pointer section shows a way to find the pair with no dictionary at all.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.