0:00 / 0:00

Find the longest run of characters with no repeats. Slide a window along the string, and when a letter repeats, jump the left edge past its last copy.

▼

The problem

LeetCode 3, Longest Substring Without Repeating Characters (Medium). Given a string, return the length of the longest substring (a contiguous run) in which no character repeats.

Example: "bcdcefb" (shown as B C D C E F B) → 5 ("dcefb").

def longest_substring(s):
    last = {}              # char -> last index
    left = best = 0
    for right, ch in enumerate(s):
        if last.get(ch, -1) >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best
TRY IT ON LEETCODE ▶

The solution

def longest_substring(s):
    last = {}              # char -> last index
    left = best = 0
    for right, ch in enumerate(s):
        if last.get(ch, -1) >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best

Transcript

Longest Substring Without Repeating Characters. You get a string. Find the length of the longest substring, a run of characters side by side, in which no character appears twice.

Take B, C, D, C, E, F, B. B, C, D is a clean run, but the next C repeats. The longest clean run is D, C, E, F, B: five characters, all different. The answer is five.

The naive way tries every start and every end, and checks each substring for repeats. Seven characters already make twenty-eight substrings. In general there are about n squared of them, and each check takes up to n steps, so that's n cubed. Even with a set, it's n squared.

Instead, slide a window. The right edge takes one new character at a time, and the window always holds a run with no repeats. A map remembers the index where each character was last seen. When the new character was last seen inside the window, the left edge jumps just past that old copy, and the window is clean again.

Let's ride it. B, C and D board: length three, the best so far. Then C arrives. The map says it was last seen at one, inside the window. So the left edge jumps from zero to two, past two cars at once. E and F board: length four, a new best. Now B arrives. It was last seen at zero, but that's behind the left edge, so it doesn't count, and nothing moves. The window grows to five, the longest.

In code, keep the map, the left edge and the best. For each character, if its last index is at least left, move left to that index plus one. Then store the new index, and update the best with the window length.

The right edge visits each character once, and the left edge only moves forward, so the time is order n. The map holds one entry per distinct character, so the space grows only with the alphabet.

Stretch right, jump left, never look back. That's Longest Substring.