Skip to the workspace
Pebellslearn by building
Two Pointers  ›  Lesson

The Sorted Squeeze: Pairs in a Sorted List

Two Sum II 12 minIn a sorted list, two pointers at the ends find a pair with a target sum by moving the left one up when the sum is too small and the right one down when it is too big.

leetcode / The Sorted Squeeze: Pairs in a Sorted List

Explore each scene at your own pace.

01 · The rule

The rule

The Sorted Squeeze: Pairs in a Sorted List

A gym keeps its weight plates on a rack sorted from lightest to heaviest: 2, 5, 7, 11, 14 and 20 kg. A lifter wants two plates that add up to exactly 18 kg. You already know one answer, the complement lookup with a dictionary. But the rack is sorted, and sorted data lets you find the pair with no dictionary at all.

The rule

Sum too small, move left up; sum too big, move right down.

Point left at the lightest plate and right at the heaviest, and add them. Too heavy? The heaviest plate is the problem, so step right down. Too light? Step left up. Just right? Done.

def sorted_pair(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return (left, right)
        if total < target:
            left += 1          # need more: the smallest value cannot help
        else:
            right -= 1         # need less: the largest value cannot help
    return None

Why is it safe to throw a value away? Suppose the total is too big. nums[right] is being added to the smallest value still in play, and the result is already too big, so with any other partner it would be even bigger. It can never be part of the answer, and dropping it loses nothing. The same argument, flipped, covers a total that is too small.

Each step drops one value, so the loop runs at most n times, and the only extra memory is two integers. Compared with the dictionary, you trade "needs sorted input" for "needs no extra memory".

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