Sliding Window · Variable size

Character Replacement Visualizer

What is Character Replacement

You may change at most k letters. Return the longest substring that can become a run of one letter. Inside a window, the changes required are the length minus the count of the most frequent letter.

ABAB
k = 2
4

Approach

Try every substringCounting the most frequent letter of every pair of ends is too slow on a long string.
Keep the window legalGrow the right edge. While length minus the most frequent count is greater than k, move the left edge and update the counts.

Interactive solution

Changes used inside the current window
for each new letter, count it
changes = length - most frequent count
while changes exceed k, drop the left letter
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 letter enters and leaves once. The alphabet is constant.
MemoryO(1)One count per letter.

Implementation

def replace_chars(s, k):
    cnt, l, best = {}, 0, 0
    for r, ch in enumerate(s):
        cnt[ch] = cnt.get(ch, 0) + 1
        while r - l + 1 - max(cnt.values()) > k:
            cnt[s[l]] -= 1
            if cnt[s[l]] == 0:
                del cnt[s[l]]
            l += 1
        best = max(best, r - l + 1)
    return best