Skip to the workspace
Pebellslearn by building
Sliding Window  ›  Lesson

Grow and Shrink: The Longest Stretch Without Repeats

Substring Without Repetition 15 minA variable sliding window grows its right edge every step and shrinks its left edge only until the window obeys the rule again, finding the longest valid stretch in one pass.

leetcode / Grow and Shrink: The Longest Stretch Without Repeats

Explore each scene at your own pace.

01 · The rule

The rule

Grow and Shrink: The Longest Stretch Without Repeats

A music app logs the songs a listener played, in order: A, B, C, B, D, A, E. The app wants the longest stretch of consecutive plays in which no song repeats, to measure how varied a session was. Checking every stretch means about n² stretches, each needing its own check. A window that grows on the right and shrinks on the left does it in one walk.

The rule

Grow the right edge; shrink the left until the window is valid again.

A variable window has no fixed size. Its right edge moves forward one item every step. When the new item breaks the rule ("no repeats"), the left edge moves forward, dropping items, until the rule holds again. After each step the window is the longest valid stretch ending at the right edge, so the best of those is the answer.

def longest_unique_run(plays):
    inside = set()                      # what the window holds right now
    left = best = 0
    for right, song in enumerate(plays):
        while song in inside:           # the newcomer would repeat: shrink
            inside.remove(plays[left])
            left += 1
        inside.add(song)
        best = max(best, right - left + 1)
    return best

There is a while inside a for, yet it is not n². Each song enters the window once, when right reaches it, and leaves at most once, when left passes it. That is at most 2n moves in total. The set gives an instant answer to "is it already inside?"

The pattern works because of one property: if a window is valid, every smaller window inside it is valid too. A stretch with no repeats stays free of repeats when you drop songs from its left. That is what makes shrinking safe, and it is the first thing to check before using a variable window.

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