Maximum Substring Length with Character Limit
StringsAuto-graded · 26 test casesLast updated
Tests sliding window technique to find the longest contiguous sequence where the number of unique characters does not exceed a threshold.
You are given a string s and a non-negative integer k. Your task is to determine the length of the longest contiguous substring where the number of unique characters does not exceed k.
Write a function that returns this maximum length as an integer.
Constraints
0 <= len(s) <= 5 * 10^40 <= k <= 50- The string
sconsists of printable ASCII characters
Edge Case Behavior
- When
kequals0, no valid substring exists (return0) - When the string is empty, return
0 - When the entire string contains
kor fewer unique characters, the answer is the full string length
Examples
Example 1
Input: max_substring_with_k_chars('eceba', 2)
Output: 3
Example 2
Input: max_substring_with_k_chars('aa', 1)
Output: 2
Hints
Hint 1
Use two pointers to maintain a window, expanding it rightward and contracting it from the left when needed
Hint 2
Track character frequencies with a dictionary; the dictionary size tells you how many distinct characters are in your current window
Hint 3
The left pointer only moves forward, never backward, giving you linear time complexity
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem calls for a sliding window with two pointers. We maintain a window spanning indices [left, right] that always satisfies the constraint: no more than k distinct characters appear within it.
As we scan through the string with the right pointer:
- Expand the window: Add the character at position
rightto our frequency map - Shrink when invalid: If the number of distinct characters exceeds
k, remove characters from the left until we're back within the limit - Track the maximum: After each expansion, record the current window size if it's the largest we've seen
The critical implementation detail is removing dictionary entries when their count drops to zero. This ensures the dictionary size accurately reflects the count of distinct characters.
Why This Works
The correctness relies on two properties of the sliding window:
- Greedy optimality: For any fixed right endpoint, the longest valid substring ending there starts at the leftmost position that keeps distinct characters ≤ k. We never need to consider starting positions further right.
- Monotonic left pointer: As the right pointer advances, the left pointer never needs to move backward. Adding a character to the right can only increase or maintain the distinct character count, never decrease it.
These properties mean we examine each position exactly once with each pointer, visiting all optimal windows.
Complexity Analysis
- Time complexity: O(n) where n is the length of the string. Although there's a nested while loop, the left pointer advances at most n times across the entire execution, making the amortized cost linear.
- Space complexity: O(min(k, Σ)) where Σ is the alphabet size. The frequency map holds at most k+1 entries (briefly, before the shrink loop executes), bounded above by the number of possible characters.
Full Solution
def max_substring_with_k_chars(s: str, k: int) -> int:
if k <= 0 or not s:
return 0
char_freq = {}
left = 0
max_length = 0
for right, char in enumerate(s):
char_freq[char] = char_freq.get(char, 0) + 1
while len(char_freq) > k:
left_char = s[left]
char_freq[left_char] -= 1
if char_freq[left_char] == 0:
del char_freq[left_char]
left += 1
max_length = max(max_length, right - left + 1)
return max_length