836. Longest stretch of a string with no repeated character
Sliding windows show up all over text processing, from n-gram filters to dedup checks. A classic warm-up asks for the longest run of characters with no repeats.
Write longest_unique_window(s). Return the length of the longest contiguous substring of s in which every character appears at most once. An empty string returns 0.
def longest_unique_window(s)Example 1
Input: longest_unique_window('abcabcbb')
Output: 3
Example 2
Input: longest_unique_window('bbbb')
Output: 1
Constraints
- 0 <=
len(s)<= 100,000
Hint 1
Track a window start index.
Hint 2
Store the last position of each character.
Hint 3
Only jump start forward, never back.
Common mistakes
- Resetting the window to empty on a repeat and losing valid characters.
- Moving start backwards on a stale index.
- Returning the substring instead of its length.
Understand the idea
A sliding window with a last-seen map keeps an invariant (no repeats inside) while scanning once. For 'pwwkew', the window is 'pw', then the second 'w' moves start to index 2, and later 'wke' reaches length 3 before the final 'w' moves start again. Time is O(n) and memory is O(size of the alphabet).