SDE & MLE Prep

424. Longest Repeating Character Replacement

Problem

You may change at most k characters of s (uppercase letters) to any other uppercase letter. Return the length of the longest substring that can then consist of a single repeated letter.

Example: s = "AABABBA", k = 1 → 4

Constraints: length ≤ 10⁵.

A window is fixable if len − (count of its most frequent char) ≤ k. Grow r; if invalid, slide l by one. maxf never needs to decrease: the answer only improves when a larger maxf appears.

Complexity: O(n) time, O(26) space.

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        cnt = Counter()
        l = maxf = 0
        for r, ch in enumerate(s):
            cnt[ch] += 1
            maxf = max(maxf, cnt[ch])
            if r - l + 1 - maxf > k:
                cnt[s[l]] -= 1
                l += 1
        return len(s) - l