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

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.
| Input | Output | Example window |
|---|---|---|
| abcabcbb | 3 | abc |
| bbbbb | 1 | b |
| pwwkew | 3 | wke |
| abba | 2 | ab |
| empty string | 0 | empty |
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
| Right | Character | Left | Window | Best |
|---|---|---|---|---|
| 0 | a | 0 | a | 1 |
| 1 | b | 0 | ab | 2 |
| 2 | b | 2 | b | 2 |
| 3 | a | 2 | ba | 2 |
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.
| Approach | Time | Auxiliary space |
|---|---|---|
| Brute force | O(n²) | O(min(n, alphabet size)) |
| Sliding window | Expected 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.