Maximum Span with Limited Character Variety
StringsAuto-graded · 26 test casesLast updated
Tests ability to apply two-pointer sliding window technique with hash map tracking to efficiently find optimal substring boundaries.
Write a function that determines the length of the longest contiguous portion of a string where the number of unique characters does not exceed a given limit.
You are given:
text: a string consisting of lowercase English letterslimit: a non-negative integer representing the maximum number of distinct characters allowed
Return the length of the longest substring that contains no more than limit distinct characters.
Constraints
0 ≤ len(text) ≤ 100,0000 ≤ limit ≤ 26textcontains only lowercase English lettersa-z- If
limitis 0, the answer is 0 (no characters allowed) - If
textis empty, the answer is 0
Examples
Example 1
Input: max_length_with_k_chars('eceba', 2)
Output: 3
Example 2
Input: max_length_with_k_chars('aa', 1)
Output: 2
Example 3
Input: max_length_with_k_chars('aabbcc', 2)
Output: 4
Example 4
Input: max_length_with_k_chars('abracadabra', 3)
Output: 5
Hints
Hint 1
Track character frequencies using a dictionary while expanding a window
Hint 2
Use two pointers: expand the right boundary to grow the window, contract the left boundary when too many distinct characters appear
Hint 3
Remove characters from your frequency map when their count drops to zero to maintain an accurate count of distinct characters
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 with two pointers that maintains a valid substring where distinct characters never exceed the limit.
Start with both pointers at the beginning. Expand the right pointer to include new characters, tracking their frequencies in a hash map. When the number of distinct characters (the size of the hash map) exceeds the limit, contract from the left by removing characters and decrementing their counts. When a character's count reaches zero, remove it from the map entirely—this keeps the map size synchronized with the actual distinct character count.
At each step after ensuring the window is valid, calculate its length and track the maximum seen so far.
Why this works: The two-pointer approach exploits monotonicity. If a window is invalid (too many distinct characters), extending it further right cannot make it valid. Conversely, if we find a valid window, we don't need to recheck smaller windows starting from the same left position. Each character enters the window exactly once (via right pointer) and exits at most once (via left pointer), giving linear time complexity.
Time Complexity: O(n) where n is the length of the input string. Each position is visited at most twice—once by the right pointer and once by the left pointer.
Space Complexity: O(min(limit, 26)) for the hash map. The map stores at most limit + 1 distinct characters during contraction, and is bounded by the alphabet size.
Solution
def max_length_with_k_chars(text: str, limit: int) -> int:
if limit <= 0:
return 0
char_freq = {}
left = 0
max_len = 0
for right, char in enumerate(text):
char_freq[char] = char_freq.get(char, 0) + 1
while len(char_freq) > limit:
left_char = text[left]
char_freq[left_char] -= 1
if char_freq[left_char] == 0:
del char_freq[left_char]
left += 1
max_len = max(max_len, right - left + 1)
return max_len