← Whiteboard questions

Longest Substring Without Repeating Characters

Find the longest stretch with all different characters

DSA, Medium, Sliding Window

Which structure or algorithm, and what does it cost.

You get a string s. A substring is a run of consecutive characters. Return the length of the longest substring in which no character appears twice. Return 0 for an empty string.

Examples

Input s = "kayaker"
Output 5
Why The longest stretch is "yaker". The second a moves the window start, and the later k is then outside the window, so it does not move it again.
Input s = "aabbcc"
Output 2
Why The string has three different characters, but no stretch holds all three without a repeat. The best is "ab" or "bc".
Input s = "abba"
Output 2
Why The longest stretch is "ab" or "ba". The second a must not pull the window start back to before the second b.

Constraints

Your answer must contain

Target Aim for O(n) time and O(k) memory, where k is the number of distinct characters.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Look at a run of consecutive characters. What makes the run stop being valid, and what would you keep when it does?

Hint 2 the approach

Testing every substring repeats a lot of work. Slide the window instead: grow its right edge one step at a time and move its left edge only when you must.

Hint 3 the key step

Remember the last position of each character. If the new character was last seen inside the window, move the left edge just past that position. Never move it backwards.

Walkthrough

Full walkthrough brute force to best

Brute force

Test every substring for a repeated character. There are about n^2 / 2 substrings and each check can cost O(n), so the time is O(n^3). For 100,000 characters that is far too slow.

Better method

For each start position, extend to the right and keep the characters in a set. Stop at the first repeat and record the length. This is O(n * k) time and O(k) memory, with k the number of kinds of character. With at most 128 kinds that is about 13 million steps, so it passes here. It works, but it scans the same stretch again from every start, and it grows with the alphabet. The window method below does not.

Best method

Keep a window from left to the current position i that holds no repeats, and a table from each character to the last position where it was seen. At position i, if the character was last seen at a position that is at least left, that copy is inside the window, so move left to that position plus 1. If the last position is below left, the old copy is already outside the window and is ignored, so left never moves backwards. Then store i and update the best length with i - left + 1. Each position is handled once, and the table moves the left edge in one jump instead of one removal at a time.

Hand trace

Run on abba. Position 0 (a): left 0, window length 1, best 1. Position 1 (b): length 2, best 2. Position 2 (b): b was last seen at 1, which is at least left 0, so left becomes 2; length 1, best stays 2. Position 3 (a): a was last seen at 0, which is below left 2, so it is ignored; the window is ba with length 2, best 2. The answer is 2.

Code

def longest(s):
    last = {}
    left = best = 0
    for i, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = i
        best = max(best, i - left + 1)
    return best

Time and memory

O(n) time, because each position is handled once with table steps that cost O(1) on average. O(k) memory for the table, where k is the number of distinct characters (at most 128 here).

Common mistakes

  • Setting left to the last position plus 1 without checking that the old copy is inside the window. For abba this gives 3, not 2.
  • Resetting the whole window at every repeat. That throws away valid characters that sit just after the repeated one.
  • Updating the best length before moving left. That counts a window that still holds a repeat.

Related problems

More Sliding Window problems
Longest Substring Without Repeating Characters walkthrough