Longest Substring with At Most K Distinct Characters Problem
Description
LeetCode Problem 340.
Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Explanation: The substring is "ece" with length 3.
Example 2:
Input: s = "aa", k = 1
Output: 2
Explanation: The substring is "aa" with length 2.
Constraints:
1 <= s.length <= 5 * 10^40 <= k <= 50
Solution
Approach: Sliding Window with a Count Map
Checking every substring is O(n2) or worse. A sliding window works because the condition is monotone: if a window has at most k distinct characters, so does every smaller window inside it.
Keep a window s[left..right] and a hash map count from each character to its number of occurrences in the window. The number of distinct characters is the size of the map.
- Move
rightforward one step at a time and adds[right]tocount. - While the map has more than
kkeys, removes[left]from the window: decrease its count, delete the key when it reaches zero, and moveleftforward. Deleting the key matters, otherwise the map size would still count a character that left the window. - The window is now valid; update the answer with
right - left + 1.
Both ends only move forward, so each character enters and leaves the window at most once. When k = 0, every window shrinks to empty, and the answer is 0.
Complexity: O(n) time, and O(k) extra space for the map, which never holds more than k + 1 characters.
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
count = {} # character -> how many times it appears in the window s[left .. right]
left = best = 0
for right, ch in enumerate(s):
count[ch] = count.get(ch, 0) + 1
while len(count) > k: # too many distinct characters: shrink from the left
out = s[left]
count[out] -= 1
if count[out] == 0:
del count[out]
left += 1
best = max(best, right - left + 1)
return best