This question asks us to find the longest window within a string where we can replace up to k
characters. This is a sliding window question, where we expand the window if we have at least one extra character or we add to the most common character. So, we do that.
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
l = 0
max_len = 0
freq = defaultdict(int)
for r, c in enumerate(s):
freq[c] += 1
curr = r - l + 1
if curr - max(freq.values()) <= k:
max_len = max(max_len, curr)
else:
freq[s[l]] -= 1
l += 1
return max_len