Track frequencies and maximum frequency. Shrink window when replacements needed exceed k.
function characterReplacement(s, k): count = {} left = 0 maxFreq = 0 maxLen = 0 for right in range(len(s)): count[s[right]] = count.get(s[right], 0) + 1 maxFreq = max(maxFreq, count[s[right]]) windowSize = right - left + 1 if windowSize - maxFreq > k: count[s[left]] -= 1 left += 1 maxLen = max(maxLen, right - left + 1) return maxLen
time, space.