Longest Window With a Capped Number of Distinct Letters
StringsAuto-graded · 22 test casesLast updated
Find the length of the longest contiguous stretch of a string using no more than k different characters, testing the sliding-window technique with a frequency map.
You are given a string text and an integer max_distinct. Look at every contiguous block of characters inside text (a substring). Among the blocks that contain no more than max_distinct different characters, find the longest one and return its length.
Characters are compared exactly as they appear in the Python string, so uppercase and lowercase letters are different characters, and each Python character (code point) counts as one character.
Edge-case rules
- If
textis empty, return0. - If
max_distinctis0or negative, no non-empty block can qualify, so return0. - If
max_distinctis at least the number of distinct characters intext, the whole string qualifies, so returnlen(text).
Task
Implement a function that returns this maximum length as an integer. Aim for a solution that runs in linear time in the length of the string.
Constraints
0 <= len(text) <= 10^5-10^5 <= max_distinct <= 10^5textis a Python string; any characters may appear.- The return value is a single non-negative integer.
Examples
Example 1
Input: longest_window_max_distinct('eceba', 2)
Output: 3
Example 2
Input: longest_window_max_distinct('aa', 1)
Output: 2
Example 3
Input: longest_window_max_distinct('aabbcc', 2)
Output: 4
Example 4
Input: longest_window_max_distinct('abaccc', 2)
Output: 4
Hints
Hint 1
Checking every substring is quadratic or worse. Think about a window described by two indices, left and right, that you move through the string.
Hint 2
Keep a dictionary of how many times each character appears in the current window. The number of keys is the number of distinct characters, as long as you remove keys whose count reaches zero.
Hint 3
For each new right index, add the character, then move left forward while the window has more than max_distinct distinct characters. After that the window is valid, so compare its length with the best so far. Handle max_distinct <= 0 and empty text up front.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a sliding window over text, defined by indices left and right, together with a dictionary that records how many times each character occurs inside the window.
- Handle the trivial cases first: if
textis empty ormax_distinct <= 0, return0. - Move
rightacross the string one position at a time, addingtext[right]to the counts. - If the dictionary now has more than
max_distinctkeys, the window is invalid. Moveleftforward, decreasing the count of the character leaving the window and deleting its key when the count hits zero, until the window is valid again. - The window is now the longest valid one ending at
right. Update the best length if it is larger.
Deleting zero-count keys is essential: it keeps the dictionary size equal to the true number of distinct characters in the window, so the validity check is O(1).
Why it is correct
Validity is monotone under shrinking: if a window has at most k distinct characters, so does every sub-window. Therefore, for a fixed right, the shrink loop stops at the smallest left giving a valid window, which is the longest valid window ending at right. Also, left never needs to move backward: if text[l..right] is invalid, then text[l..r] is invalid for every r > right. Every substring ends at some index, so taking the maximum over all right gives the global answer.
Complexity
- Time: O(n). Each index enters the window once and leaves at most once, and dictionary operations are O(1) on average.
- Space: O(min(n, k + 1)) for the dictionary, since it never holds more than
k + 1keys.
Reference solution
from typing import Dict
def longest_window_max_distinct(text: str, max_distinct: int) -> int:
if max_distinct <= 0 or not text:
return 0
counts: Dict[str, int] = {}
left = 0
best = 0
for right, ch in enumerate(text):
counts[ch] = counts.get(ch, 0) + 1
while len(counts) > max_distinct:
old = text[left]
counts[old] -= 1
if counts[old] == 0:
del counts[old]
left += 1
best = max(best, right - left + 1)
return best