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
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 letter enters and leaves once. The alphabet is constant. |
| Memory | O(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