Skip to the workspace
Pebellslearn by building
Two Pointers  ›  Capstone Project

Move the Shorter Side: Greedy Pointer Moves

Container With Most Water 15 minWhen the value of a pair is capped by its smaller side, sweeping two pointers inward and always moving the smaller side finds the best pair in one pass, because the smaller side can never do better.

leetcode / Move the Shorter Side: Greedy Pointer Moves

Explore each scene at your own pace.

01 · The rule

The rule

Move the Shorter Side: Greedy Pointer Moves

A row of poles stands one metre apart, with heights 3, 7, 2, 6, 4 and 8 metres. You will hang a rectangular banner between two of them. Its width is the distance between the poles, and its height is limited by the shorter pole, because the banner cannot hang higher than either support. Which two poles give the biggest banner? Checking all pairs works; one inward sweep is enough.

The rule

The shorter side caps the area, so move the shorter side.

Start with the two outermost poles: the widest banner possible. Every move inward costs one metre of width, so a move is only worth making if it could buy more height. Move the taller pole and the height is still capped by the shorter one, so the area can only shrink. Move the shorter pole and at least there is a chance of a taller partner.

def biggest_banner(heights):
    left, right = 0, len(heights) - 1
    best = 0
    while left < right:
        area = min(heights[left], heights[right]) * (right - left)
        best = max(best, area)
        if heights[left] < heights[right]:
            left += 1            # the left pole is the cap: drop it
        else:
            right -= 1           # the right pole is the cap (or a tie): drop it
    return best

Why is dropping the shorter pole safe? Every pair it could still form uses a pole nearer to it, so the width is smaller, and the height can never exceed the short pole itself. None of those pairs can beat the area you just measured. The pole has been used up, and discarding it loses nothing. One sweep, n steps, constant 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.