Longest Repeating Character Replacement – Solution & Complexity

Solution Walkthrough

  1. Step 1: Define window validity

    • A window s[left..right] can be turned into one repeated character if the number of characters that are not the most frequent letter is at most k.
    • In symbols: (right - left + 1) - max_freq <= k.
  2. Step 2: Why max_freq only needs to grow

    • Expand right one step at a time, increment counts[s[right]], and update max_freq = max(max_freq, counts[s[right]]).
    • Whenever (right - left + 1) - max_freq > k, decrement counts[s[left]] and advance left by 1.
    • Keeping max_freq as the historical high-water mark is safe because a shorter window or a smaller max_freq can never beat the best length we have already found.
  3. Step 3: Optimal O(n) sliding window

    • Single pass over s with a fixed 26-slot frequency table: O(n) time and O(1) extra space.
    def character_replacement(s: str, k: int) -> int:
        counts = [0] * 26
        left = 0
        max_freq = 0
        best = 0
        for right, ch in enumerate(s):
            idx = ord(ch) - ord("A")
            counts[idx] += 1
            if counts[idx] > max_freq:
                max_freq = counts[idx]
            while (right - left + 1) - max_freq > k:
                counts[ord(s[left]) - ord("A")] -= 1
                left += 1
            if right - left + 1 > best:
                best = right - left + 1
        return best
  4. Step 4: Common mistakes

    • Assuming the target character must be s[left]: "ABBB" with k = 2 turns 'A' into 'B', not 'B' into 'A'.
    • Re-scanning all 26 counts on every shrink step works in O(26n) but isn't needed.

FAQ