Sliding Window · Variable size

Longest K Distinct Visualizer

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

Test every substringCounting the distinct letters of every pair of ends repeats the same scan.
Keep a count of the open windowAdd the new character. While more than k keys have a positive count, decrement the left character and drop it when its count hits zero.

Interactive solution

The window and the letters currently inside it
for each new character:
add it to the counts
while more than k letters remain, drop the left character
best = max(best, length)
return best
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each character enters and leaves once.
MemoryO(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