Skip to content
Back to notes
Oct 20, 2026
Medium

Longest Substring Without Repeating Characters

"longest contiguous run where a condition holds" → sliding window. r always advances; when adding s[r] would break the condition, shrink from the left until it holds again; then record r - l + 1. Every element enters and leaves once, so the nested while is still O(n). If you can compute where l must go (here: one past the last copy of s[r]), jump there directly with a last-index map.
  • string
  • hash set
  • hash map
  • sliding window

Problem

Given a string s, find the length of the longest substring without duplicate characters. A substring is a contiguous sequence of characters within a string.

Example 1

Input:  s = "zxyzxyz"
Output: 3

The string "xyz" is the longest without duplicate characters.

Example 2

Input:  s = "xxxx"
Output: 1

Constraints

  • 0 <= len(s) <= 50,000
  • s may consist of printable ASCII characters.

Thinking

  • Brute force idea: for every start i, extend to the right with a hash set until a character repeats, and keep the longest run. O(n⋅σ)O(n \cdot \sigma), where σ\sigma is the alphabet size (a run can’t be longer than σ\sigma), so O(n2)O(n^2) when the alphabet is unbounded.
  • Key insight: when the brute force restarts at i + 1, it re-checks characters it already knows are distinct. Instead keep a window [l, r] that is always duplicate-free: r advances one step at a time, and when s[r] is already in the window, move l right (removing s[l] from the set) until it isn’t. Each character enters and leaves the window at most once → O(n)O(n).
  • Faster shrink: remember the last index of every character. On a repeat, l can jump straight to last[c] + 1, with no inner loop. Guard it with max(l, ...): an old index that is already left of l must not move the window backwards.
  • Edge cases to remember: empty string (→ 0); all the same character ("xxxx" → 1); all distinct (→ len(s)); the repeat is not at the window’s left end ("dvdf" → 3: keep "v", drop only the first "d"); the duplicate is the character just before r ("abccd" → 3); a character last seen before l ("abba" → 2: the old a must not pull l back); spaces and punctuation count as characters.

Solution

Approach A — mine: sliding window + hash set

Complexity: Time O(n)O(n) · Space O(min⁡(n,σ))O(\min(n, \sigma))

Already optimal in Big-O. Each iteration does the same three steps: shrink (remove s[l] and advance l while s[r] is still in the window), add s[r], update the best length. The inner while doesn’t make it O(n2)O(n^2): every character is added once and removed at most once, so the total work is 2n2n. Polish only: starting max_l at 0 makes the if not s guard unnecessary.

def length_of_longest_substring_mine(s: str) -> int:
    if not s:  # unnecessary if max_l starts at 0
        return 0
    l, max_l = 0, 1
    s_set = set()

    for r in range(len(s)):
        while s[r] in s_set:  # shrink until s[r] can join; amortised O(1) per character
            s_set.remove(s[l])
            l += 1
        s_set.add(s[r])
        max_l = max(max_l, r - l + 1)

    return max_l

Approach B — brute force: extend from every start

Complexity: Time O(n⋅σ)O(n \cdot \sigma) · Space O(σ)O(\sigma)

For each start, grow a run until the first repeat. Obviously correct, so the tests use it as the reference on random strings. With only ~95 printable characters each run is short, so it’s less hopeless than O(n2)O(n^2), but it still re-scans the same characters over and over.

def length_of_longest_substring_brute(s: str) -> int:
    best = 0
    for i in range(len(s)):
        seen = set()
        for c in s[i:]:  # restarts from scratch for every i
            if c in seen:
                break
            seen.add(c)
        best = max(best, len(seen))
    return best

Approach C — sliding window + last-index map ✅ best practice

Complexity: Time O(n)O(n) · Space O(min⁡(n,σ))O(\min(n, \sigma))

The version to remember. Same window as A, but the dict stores where each character was last seen, so on a repeat l jumps straight past it instead of walking there one step at a time. Characters are never removed from the dict; the >= l check ignores entries that are already outside the window (that’s the "abba" trap).

def length_of_longest_substring(s: str) -> int:
    last = {}  # char -> index where it was last seen
    l = best = 0
    for r, c in enumerate(s):
        if last.get(c, -1) >= l:  # repeat inside the window: jump past it
            l = last[c] + 1
        last[c] = r
        best = max(best, r - l + 1)
    return best

Scratch / Experiments

Worst case for the brute force: the 95 printable characters repeated in a cycle up to the max length n=50,000n = 50{,}000, so every start scans a full run of 95 before hitting a repeat. A random string is also timed, where runs are short and the brute force looks much better than it is.

Measured (n=50,000n = 50{,}000): on the cyclic string, last-index map ~4.6 ms, mine ~5.9 ms, brute force ~183 ms (~30× slower). On the random string, map ~3.9 ms, mine ~7.0 ms, brute force ~55 ms.

Both windows are O(n)O(n), but the map version is consistently faster: it does one dict lookup and one store per character, while the set version also does a remove + l += 1 for every character that leaves the window (up to 2n2n set operations in total). The brute force is only ~10–30× slower rather than thousands of times, because σ≈95\sigma \approx 95 caps every run; with an unbounded alphabet it would be truly O(n2)O(n^2).

chars = string.printable[:95]
cyclic = (chars * (50_000 // len(chars) + 1))[:50_000]
rng = random.Random(0)
random_s = "".join(rng.choice(chars) for _ in range(50_000))

for s in (cyclic, random_s):
    assert length_of_longest_substring_mine(s) == length_of_longest_substring(s) == length_of_longest_substring_brute(s)
    %timeit length_of_longest_substring_mine(s)
    %timeit length_of_longest_substring(s)
    %timeit -n 1 -r 3 length_of_longest_substring_brute(s)

Takeaways

  • Pattern: “longest contiguous run where a condition holds” → sliding window. r always advances; when adding s[r] would break the condition, shrink from the left until it holds again; then record r - l + 1. Every element enters and leaves once, so the nested while is still O(n)O(n). If you can compute where l must go (here: one past the last copy of s[r]), jump there directly with a last-index map.
  • Mistakes I made (in earlier drafts, before the final version):
    • Changing r inside for r in range(...) (r + 1, r = l + 1, r += 1): the for overwrites it on the next iteration, so it does nothing or only works by accident. Compute lengths from r and l instead.
    • Never removing characters from the set when l moved, so characters outside the window still counted as duplicates. The set must hold exactly the window.
    • Removing s[r] instead of s[l]: the character that leaves when l moves is the one on the left.
    • Moving l by one step (or jumping to r) instead of until the duplicate is gone → use a while.
    • Splitting the loop into if / else and forgetting to add s[r] and update the answer in the else. The fix was one shape for every iteration: shrink → add → update.
    • Tests that only cover the examples pass by luck: "dvdf", "abccd" and "abba" are the cases that actually exercise the shrink.
  • Related problems: Best Time to Buy and Sell Stock (#121, the simpler window where l jumps on a new low); Longest Repeating Character Replacement (#424, window valid while len - max_count <= k); Permutation in String (#567) and Find All Anagrams (#438, fixed-size window with counts); Minimum Window Substring (#76, the “shortest” version: grow until valid, then shrink); Longest Substring with At Most K Distinct Characters (#340, same shape with a count map).