What is Longest K Distinct
Return the length of the longest substring that uses at most k different characters. Grow the right edge. When the window has too many different characters, move the left edge until it is legal again.
eceba k = 2 3
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each character enters and leaves once. |
| Memory | O(k) | The count table holds at most k + 1 keys. |
Implementation
def longest_k(s, k):
if k <= 0:
return 0
cnt, l, best = {}, 0, 0
for r, ch in enumerate(s):
cnt[ch] = cnt.get(ch, 0) + 1
while len(cnt) > k:
cnt[s[l]] -= 1
if cnt[s[l]] == 0:
del cnt[s[l]]
l += 1
best = max(best, r - l + 1)
return best