Longest Window of Unique Characters
StringsAuto-graded · 27 test casesLast updated
Tests whether a candidate can apply a sliding window with a character index map to find the longest contiguous run of non-repeating characters.
Problem
You are given a string s. Return the length of the longest contiguous portion of s in which every character appears exactly once.
If s is empty, return 0.
What counts as a valid window
A window is any contiguous slice of s. It is valid when no character in that slice occurs more than once. You want the length of the longest such valid window.
Note that you are looking for a substring (contiguous), not a subsequence (characters may be spread out).
Constraints
0 <= len(s) <= 5 * 10^4smay contain uppercase and lowercase English letters, decimal digits, symbols, and space characters.
Examples
Example 1
Input: longest_unique_window('abcabcbb')
Output: 3
Example 2
Input: longest_unique_window('bbbbb')
Output: 1
Example 3
Input: longest_unique_window('pwwkew')
Output: 3
Hints
Hint 1
Try maintaining a window defined by a left and a right pointer. Grow the window by advancing the right pointer one step at a time, and only move the left pointer when the window becomes invalid.
Hint 2
Store the most recent index at which each character was seen. When the character at `right` already appears somewhere inside the current window, you can jump `left` directly past that earlier occurrence rather than shrinking one step at a time.
Hint 3
Be careful not to move `left` backward. If a character was last seen before the current window started, that occurrence is already outside the window and can be ignored. The string "abba" is a good case to trace through by hand to check this.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why brute force is too slow
Checking every possible substring and scanning each one for duplicates costs O(n²) to O(n³). For strings up to 50 000 characters that is too slow.
Sliding window with a last-seen map
The core idea is to keep a window s[left..right] that is always valid (all characters distinct), and extend it as far as possible before recording its length.
- Walk
rightfrom0tolen(s) - 1. - At each step, look up
s[right]in a dictionary that maps each character to the last index where it appeared. - If that previous index exists and falls inside the current window (i.e.,
>= left), then the window now has a duplicate. Jumplefttoprevious_index + 1in a single step, which is the earliest position that excludes the earlier copy. - Always update
last_seen[s[right]]toright, then record the new window length.
The result is the maximum window length seen across all positions.
Why left must never move backward
If a character's last recorded position is before left, that occurrence is already outside the window and is harmless. Without the >= left guard, a stale entry could pull left backward and produce an invalid window. Tracing "abba" makes this clear:
- When the final
ais processed,last_seen['a'] = 0, butleftis already2. Jumping back to1would create the window"bba", which has a repeatedb. The guard prevents this.
Writing left = max(left, last_seen[char] + 1) is an equivalent and idiomatic way to express the same constraint.
Correctness
Invariant: after processing index right, the slice s[left..right] contains no duplicate characters, and left is the smallest index for which that holds.
Because left is always minimal, the window is the longest valid window ending at right. Taking the maximum over all ending positions gives the globally longest valid window.
Edge cases
| Input | Expected | Why |
|---|---|---|
"" | 0 | Loop never runs; best stays 0. |
"bbbbb" | 1 | left chases right at every step. |
"abcdef" | 6 | No repeats; left stays at 0. |
"abba" | 2 | Stale a at index 0 must not pull left back. |
" " | 1 | Space is an ordinary character. |
Complexity
- Time: O(n). Each character is visited exactly once by
right. Every dictionary lookup and write is O(1) average.leftonly advances forward, so no character is revisited. - Space: O(min(n, k)) where
kis the size of the character set. The dictionary holds at most one entry per distinct character. For printable ASCII that is a fixed upper bound of roughly 95 entries, effectively O(1).
Full solution
def longest_unique_window(s: str) -> int:
last_seen = {} # char -> most recent index at which it appeared
left = 0 # left boundary of the current valid window
best = 0
for right, char in enumerate(s):
# If this character appeared before AND that occurrence is still
# inside the current window, move the left boundary just past it.
if char in last_seen and last_seen[char] >= left:
left = last_seen[char] + 1
last_seen[char] = right
best = max(best, right - left + 1)
return best