Longest Substring with At Most K Distinct Characters
Longest Substring with At Most K Distinct Characters is LeetCode 340 (Medium). Given a string s and a number k, return the length of the longest substring that uses no more than k different characters.
- A character may repeat any number of times; only the number of different ones is limited.
scan hold 50,000 characters andkgoes up to 50, so the answer must come from one pass overs.
- 1 <= s.length <= 5 * 10⁴
- 0 <= k <= 50
Intuition
A substring that keeps to the limit still keeps to it after you trim either end, and one that breaks the limit stays broken if you add characters. Because of that one-way behaviour, one window that only ever moves forward finds the answer: grow the right end, and when the window holds k + 1 different characters, pull the left end in until one of them has left completely.
- A map of counts: store how many times each character appears in the window. The number of keys is the number of different characters.
- Left completely: a character stops counting only when its last copy leaves the window.
"Longest stretch with at most k kinds of something" is a two-pointer window over a count map. Fruit Into Baskets is this problem with k fixed at 2.
Approach
Before reading on: what single number tells you a window has broken the limit, and which end should move to fix it? Aim for O(n) time.
Grow the window one character at a time
For each right, add one to count[s[right]]. If the character was already in the window its count rises; if not, a new key appears and the window holds one more different character.
Pull the left end in while there are too many keys
While count has more than k keys, take one from count[s[left]] and step left forward. Each pass removes one character from the window, so the loop stops once a whole character is gone.
Delete a key only when its count reaches 0
When count[s[left]] drops to 0, delete that key. Until then, another copy of the character is still inside the window and still counts toward the limit.
Record the window
With at most k keys left, right - left + 1 is a valid length; keep the largest one in best and return it when the loop ends.
Code in Python, C++ and Java
Common pitfalls
Leaving a key in the map at count 0
count[s[left]] -= 1 left += 1
count[s[left]] -= 1
if count[s[left]] == 0:
del count[s[left]]
left += 1The map size is the test, and a key at 0 still adds to it. On "eceba" with k = 2 the size never drops back to 2, so left runs past right into characters not yet added, and the code crashes with a KeyError instead of returning 3.
A 26-slot array for the counts
int count[26] = {};
count[s[right] - 'a']++;unordered_map<char, int> count; count[s[right]]++;
The problem does not promise lowercase letters, and k going up to 50 hints that more than 26 characters can appear. An uppercase letter in "aBc" indexes far outside the array.
Edge cases
Every new character makes one key, which is already too many, so the left end passes it at once. The window stays empty and the answer is 0.
The map never passes the limit, the left end never moves, and the answer is the whole length.
Complexity
Longest Substring with At Most K Distinct Characters FAQ
How is this different from Longest Repeating Character Replacement?
There any letters may sit in the window as long as at most k of them need changing. Here nothing is changed, and k caps how many different characters the window may hold.
What if the question asks for exactly k distinct characters?
Run the same window, but record a length only when the map has exactly k keys, and return -1 if that never happens. On "aaab" with k = 3 the at-most answer is 4, while no substring has exactly 3.
Is this the same as Fruit Into Baskets?
Yes, with k fixed at 2. Each fruit type is a character, the two baskets are the two allowed keys, and the most fruit you can pick is the longest valid window.