Longest Substring with At Most K Distinct Characters
Pattern: Sliding window: variable size
Count each character in the window and track how many different ones there are. When that number goes above k, shrink from the left until it is k again.
The problem
Given a string and a number k, return the length of the longest block of neighbouring characters that uses at most k
different characters. For example, "eceba" with k = 2 gives 3 ("ece"), "aa" with k = 1 gives 2, and any string
with k = 0 gives 0.
The function name lengthOfLongestSubstringKDistinct matches LeetCode, where this is a premium problem. The statement
here is complete, so you can solve it without the link.
Think first
- How is this the same as Fruit Into Baskets?
- What do you need to store to know how many different characters are in the window?
- When a character leaves the window, when does the "different" count go down?
Hints
Brute force, and why it fails
From each start, extend until there are k + 1 different characters: O(n²). The window is O(n).
The key insight
"At most k different characters" only gets harder to satisfy as the window grows, so the longest-window template works. The count array makes adding and removing a character O(1).
Dry run
| distinct | 2 |
|---|---|
| best | 3 |
s = eceba and k = 2. The window e, c, e has two different characters and length 3.
The plan
count = all zeros, distinct = 0, left = 0, best = 0
for right from 0 to n - 1:
if count[s[right]] == 0: distinct = distinct + 1
count[s[right]] = count[s[right]] + 1
while distinct > k:
count[s[left]] = count[s[left]] - 1
if count[s[left]] == 0: distinct = distinct - 1
left = left + 1
best = max(best, right - left + 1)
return best
Complexity
- Time
O(n)- Space
O(alphabet)
Each edge moves at most n times. The count array has one slot per possible character (128 for ASCII).
Edge cases
k = 0: every non-empty window breaks the rule, so the answer is 0.kat least the number of different characters ins: the whole string.- A single character: 1, as long as
kis at least 1.
I've built my logic, show the code
Java
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int[] count = new int[128]; // how many of each character are in the window
int distinct = 0, left = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
if (count[s.charAt(right)]++ == 0) distinct++;
while (distinct > k) { // too many kinds: shrink from the left
if (--count[s.charAt(left)] == 0) distinct--;
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
}C++
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
vector<int> count(128, 0); // how many of each character are in the window
int distinct = 0, left = 0, best = 0;
for (int right = 0; right < static_cast<int>(s.size()); right++) {
if (count[static_cast<unsigned char>(s[right])]++ == 0) distinct++;
while (distinct > k) { // too many kinds: shrink from the left
if (--count[static_cast<unsigned char>(s[left])] == 0) distinct--;
left++;
}
best = max(best, right - left + 1);
}
return best;
}
};Python
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
count = {} # how many of each character are in the window
left = best = 0
for right, c in enumerate(s):
count[c] = count.get(c, 0) + 1
while len(count) > k: # too many kinds: shrink from the left
old = s[left]
count[old] -= 1
if count[old] == 0:
del count[old]
left += 1
best = max(best, right - left + 1)
return bestCommon mistakes
- Using a set of characters instead of counts, so you cannot tell when the last copy of a character leaves.
- Updating
distincton every add, not only when a count goes from 0 to 1. - Returning the number of different characters instead of the window length.