Maximum Distinct Character Window
StringsAuto-graded · 21 test casesLast updated
Tests sliding window technique with hash maps to find the longest contiguous span of non-repeating characters in a string.
You are given a string s. Your task is to find the length of the longest contiguous substring where all characters are distinct (no character appears more than once).
A substring is a consecutive sequence of characters within the string. For instance, "abc" is a substring of "abcabcbb", but "ac" is not (it skips "b").
Return an integer representing the length of the longest such substring.
Constraints:
0 <= len(s) <= 50,000sconsists of any printable characters including letters, digits, spaces, and symbols- Characters are case-sensitive:
'A'and'a'are treated as different characters - If the string is empty, return
0
Examples
Example 1
Input: max_distinct_window('abcabcbb')
Output: 3
Example 2
Input: max_distinct_window('bbbbb')
Output: 1
Example 3
Input: max_distinct_window('pwwkew')
Output: 3
Example 4
Input: max_distinct_window('')
Output: 0
Hints
Hint 1
Consider maintaining a window that expands and contracts as you scan through the string from left to right.
Hint 2
Use a dictionary to remember where each character last appeared, so you can quickly detect when a duplicate enters your current window.
Hint 3
When you encounter a character that already exists in your current window, you need to shrink the window from the left, but be careful not to move the left boundary backward.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to use a sliding window technique combined with a hash map. We maintain a window of characters that are all distinct, expanding it to the right and contracting from the left when necessary.
The algorithm works by iterating through the string with a right pointer. For each character, we check if it has appeared before within our current window. We track the most recent position of each character using a dictionary.
When we encounter a character that already exists in the current window (meaning its last-seen index is at or after our left boundary), we must shrink the window by moving the left pointer to just after the previous occurrence of that character. This ensures the window remains duplicate-free.
A critical detail: the dictionary is never cleared, so it may contain indices that lie outside the current window (to the left of our left pointer). We must verify that last_seen[char] >= left before considering it a true conflict. Without this check, we might incorrectly move the left pointer backward, which would reintroduce duplicates into the window.
After processing each character, we update the maximum window length seen so far. The answer is this maximum across all positions.
Why It Works
The algorithm maintains an invariant: after processing index right, the substring s[left:right+1] contains no duplicate characters, and left is the smallest index that makes this true.
When we add a new character at position right, if it creates a duplicate with a character at position j where j >= left, then every window starting at or before j and ending at right contains that duplicate. The smallest valid starting position is therefore j + 1.
Since we only move left forward (or keep it the same), we maintain the property that for each ending position, we have the longest possible valid window. Taking the maximum over all ending positions gives us the globally optimal answer.
Complexity
Time complexity: O(n), where n is the length of the string. We iterate through the string once, and each character is processed in constant time with the dictionary operations.
Space complexity: O(min(n, k)), where k is the size of the character set. The dictionary stores at most one entry per distinct character. For ASCII this is effectively O(1), but for arbitrary Unicode it's bounded by the string length.
Solution
def max_distinct_window(s: str) -> int:
last_seen = {}
left = 0
best = 0
for right, char in enumerate(s):
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