Longest Substring Without Repeating Characters: Sliding Window Explained

Medium · Sliding window · Python. Prerequisites: strings, hash maps and loops.

Sliding window walkthrough for abba, showing duplicate b and final maximum length of two.
The window expands, moves left on a duplicate, and finds a maximum length of 2.

Imagine scanning a stream of characters to find the longest uninterrupted segment without duplicates. Restarting at every character wastes work. A sliding window remembers what is already valid.

Problem and examples

Given a string s, return the length of its longest contiguous substring containing no repeated characters. A substring is contiguous; a subsequence need not be.

InputOutputExample window
abcabcbb3abc
bbbbb1b
pwwkew3wke
abba2ab
empty string0empty

Constraints and edge cases

Allow an empty string, repeated characters, spaces and Unicode code points. For large inputs, quadratic work becomes expensive; aim for a single pass. A substring must remain contiguous.

Pattern recognition: When a problem asks for the longest contiguous segment satisfying a condition, consider a variable-length sliding window. Here, adding a character can violate uniqueness, and removing characters from the left restores it.

Brute force

Start at every index, extend a set until a duplicate appears, and track the maximum. Worst-case time O(n²), auxiliary space O(min(n, alphabet size)).

def brute(s):
    best = 0
    for i in range(len(s)):
        seen = set()
        for j in range(i, len(s)):
            ch = s[j]
            if ch in seen:
                break
            seen.add(ch)
            best = max(best, len(seen))
    return best

The brute-force method repeatedly examines overlapping windows. For example, after examining abc in abcabcbb, starting again at b repeats work. Instead, retain the valid suffix and discard only the prefix that causes a duplicate.

Optimize using a sliding window

  • Maintain left and right boundaries of a duplicate-free window.
  • Store the latest index of each character.
  • When a duplicate lies inside the window, jump left beyond its previous occurrence.
  • Update the best length after restoring the invariant.

Visual walkthrough

Index:     0  1  2  3
String:    a  b  b  a

Step 1:   [a] b  b  a    best = 1
Step 2:   [a  b] b  a    best = 2
Step 3:    a  b [b] a    best = 2
Step 4:    a  b [b  a]   best = 2

The brackets show the valid window after each character is processed. At step 3, the repeated b forces left to jump to index 2. At step 4, the old a is outside the window, so left stays at 2.

Dry run: abba

RightCharacterLeftWindowBest
0a0a1
1b0ab2
2b2b2
3a2ba2

The last a was at index 0, outside the current window. Never move left backward. This is the most common bug.

Python solution

def longest_unique(s: str) -> int:
    last = {}
    left = best = 0
    for right, ch in enumerate(s):
        left = max(left, last.get(ch, -1) + 1)
        last[ch] = right
        best = max(best, right - left + 1)
    return best

assert longest_unique('abba') == 2
assert longest_unique('') == 0
assert longest_unique('pwwkew') == 3

Complexity and correctness

Expected O(n) time with hash maps. Python uses O(min(n, alphabet size)) map space. The invariant is that the current window contains no duplicate. Moving left beyond the previous occurrence restores it while preserving the longest valid suffix ending at right.

ApproachTimeAuxiliary space
Brute forceO(n²)O(min(n, alphabet size))
Sliding windowExpected O(n)O(min(n, alphabet size))

Common mistakes

Do not move left backward when a previous occurrence is outside the window. Update the last occurrence only after using its old value. Compute the inclusive length as right minus left plus one. Initialize best to zero to handle empty input.

Interview practice

Why use max(left, previous + 1)?

A previous occurrence may be outside the active window. Taking the maximum prevents the left boundary from moving backward and reintroducing duplicates.

Why not sort the string?

Sorting changes character order and destroys the contiguous substring property.

Why is the algorithm linear?

The right pointer visits each character once and the left pointer only moves forward. Hash map operations take expected constant time.

What is the window invariant?

After adjusting left, every character in the active window is unique. It is the longest valid suffix ending at right.

Related problem variations

Try these independently: return the longest unique substring itself; longest substring with at most K distinct characters; minimum window substring; longest repeating character replacement; process an incoming character stream.

Try it yourself

Trace dvdf by hand before running the code. Then test all-identical strings, all-distinct strings and strings containing spaces. Compare against the brute force implementation on randomly generated short strings.

Quick revision

Variable-length sliding window: expand right, restore validity, update answer. Never move left backward. Practice the original problem at LeetCode.

Scroll to Top