LeetCode #340 Medium

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.
  • s can hold 50,000 characters and k goes up to 50, so the answer must come from one pass over s.
Constraints
  • 1 <= s.length <= 5 * 10⁴
  • 0 <= k <= 50
sliding-windowhashmapstrings
Open on LeetCode ↗
02

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.
How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
▶3 count = {}
▶4 left = best = 0
▶5 for right, ch in enumerate(s):
▶6 count[ch] = count.get(ch, 0) + 1
▶7 while len(count) > k:
▶8 out = s[left]
▶9 count[out] -= 1
▶10 if count[out] == 0:
▶11 del count[out]
▶12 left += 1
▶13 best = max(best, right - left + 1)
▶14 return best
e0c1e2b3a4window emptymap: room for 2 keysfreefree0bestempty map, room for 2 keys
left0
keys0limit 2
best0
The map will hold one key per different character in the window, with its count. It has room for 2 keys; a key in the slot past the dashed line means the window breaks the limit.
e0c1e2b3a4length 1map: room for 2 keyse×1free1bestadd e → new key, 1 key → best 1
left0
keys1limit 2
best1
e is not in the window yet, so it gets a new key. At most 2 different characters, and 1 is the longest window so far.
e0c1e2b3a4length 2map: room for 2 keyse×1c×12bestadd c → new key, 2 keys → best 2
left0
keys2limit 2
best2
c is not in the window yet, so it gets a new key. At most 2 different characters, and 2 is the longest window so far.
e0c1e2b3a4length 3map: room for 2 keyse×2c×13bestadd e → e count 2 → best 3
left0
keys2limit 2
best3
e is already in the window, so only its count rises; the number of keys stays 2. At most 2 different characters, and 3 is the longest window so far.
e0c1e2b3a4length 4map: room for 2 keyse×2c×1one too manyb×13bestadd b → new key, 3 keys, too many
left0
keys3limit 2
best3
b is not in the window yet, so it gets a new key. The map now has 3 keys, one more than k = 2, so the left end must move until one character has left completely.
e0c1e2b3a4length 3map: room for 2 keyse×1c×1one too manyb×13bestdrop e → count 1, key stays
left1
keys3limit 2
best3
Remove e at index 0 from the left. Another e is still inside the window, so the key stays and the map still has 3 keys. Keep moving left.
e0c1e2b3a4length 2map: room for 2 keyse×1c×0one too manyb×13bestdrop c → count 0, delete key
left2
keys3limit 2
best3
Remove c at index 1 from the left. That was its last copy, so its count is 0 and the key is deleted: the window is back to 2 keys and 2 long.
e0c1e2b3a4length 3map: room for 2 keyse×1b×1one too manya×13bestadd a → new key, 3 keys, too many
left2
keys3limit 2
best3
a is not in the window yet, so it gets a new key. The map now has 3 keys, one more than k = 2, so the left end must move until one character has left completely.
e0c1e2b3a4length 2map: room for 2 keyse×0b×1one too manya×13bestdrop e → count 0, delete key
left3
keys3limit 2
best3
Remove e at index 2 from the left. That was its last copy, so its count is 0 and the key is deleted: the window is back to 2 keys and 2 long.
e0c1e2b3a4length 3map: room for 2 keysb×1a×13bestanswer: 3
answer3
The longest window that never held more than 2 different characters is marked in green: 3 long.
05

Common pitfalls

Leaving a key in the map at count 0

✗ Wrong
count[s[left]] -= 1
left += 1
✓ Right
count[s[left]] -= 1
if count[s[left]] == 0:
    del count[s[left]]
left += 1

The 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

✗ Wrong
int count[26] = {};
count[s[right] - 'a']++;
✓ Right
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.

06

Edge cases

k = 0

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.

k is at least the number of different characters in s

The map never passes the limit, the left end never moves, and the answer is the whole length.

07

Complexity

Time
O(n)
Space
O(k)
Each character enters the window once and leaves at most once. The map holds at most k + 1 keys, and only until the left end catches up.
08

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.