PracticeNeetCode ↗LeetCode ↗
Given a string s of uppercase letters and an integer k, you may replace up to k characters in the string with any other uppercase letter. Return the length of the longest substring containing a single repeating character you can achieve after at most k replacements.
(window length) - (count of its most frequent character) <= k — that difference is exactly how many characters would need replacing.left = 0, a character count map, max_freq = 0, and result = 0.right: increment the count for s[right], then update max_freq.(right - left + 1) - max_freq > k: decrement the count for s[left] and move left forward.result with the current window size.result.Time: O(n) — Space: O(1) (26 letters)
def characterReplacement(s: str, k: int) -> int:
count = {}
left = 0
max_freq = 0
result = 0
for right in range(len(s)):
ch = s[right]
count[ch] = count.get(ch, 0) + 1
max_freq = max(max_freq, count[ch])
while (right - left + 1) - max_freq > k:
count[s[left]] -= 1
left += 1
result = max(result, right - left + 1)
return resultHow the solution above works, piece by piece.
window length − max_freq ≤ k: keep the most common letter and replace everything else, which takes that many edits.s[right] to count and update max_freq.k replacements, drop s[left] and move left right.result tracks the biggest valid window.max_freq is never decreased when shrinking. That's safe: the answer can only improve when a higher frequency appears, so a stale value never produces a wrong result. O(n) time, O(26) space.Running it on s = "AABABBA", k = 1:
AABA → AAAA.