Longest Repeating Character Replacement

Pattern: Sliding window: variable size

medium

A window can be made all one letter when its length minus its most common letter's count is at most k. Grow the window, and shrink it when more than k letters would need changing.

The problem

You are given a string of uppercase English letters and a number k. You may change at most k letters, each into any uppercase letter. Return the length of the longest block of one repeated letter you can then have. For example, "ABAB" with k = 2 gives 4, and "AABABBA" with k = 1 gives 4 (change the B at index 2 to get "AAAA" at the start).

The function name characterReplacement matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • For one fixed block, which letter should every other letter be changed into?
  • How many changes does that block then need?
  • As the window grows, does it ever matter that the most common count you remember is slightly out of date?

Hints

    Brute force, and why it fails

    Check every block, keeping counts as it grows from each start: O(n²·26) or O(n²). The window is O(n).

    The key insight

    "Can be made one letter with k changes" means "length minus the top count is at most k". That rule only gets harder as the window grows, so the longest-window template applies, with one extra number, the top count.

    Dry run

    A0left
    A1 
    B2right
    A3 
    B4 
    B5 
    A6 
    maxFreq2
    best3

    s = AABABBA and k = 1. The window A, A, B has length 3 and its most common letter (A) appears twice. 3 - 2 = 1 change, which is allowed.

    Step 1 of 4

    The plan

    count = 26 zeros, left = 0, maxFreq = 0, best = 0
    for right from 0 to n - 1:
        count[s[right]] = count[s[right]] + 1
        maxFreq = max(maxFreq, count[s[right]])
        while (right - left + 1) - maxFreq > k:
            count[s[left]] = count[s[left]] - 1
            left = left + 1
        best = max(best, right - left + 1)
    return best
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Each edge moves at most n times. The counts take 26 slots, whatever the length.

    Edge cases

    • k = 0: the longest run of one letter already there.
    • k at least n: the whole string.
    • All letters different, as in "ABCDE" with k = 1: 2.
    I've built my logic, show the code

    Java

    class Solution {
        public int characterReplacement(String s, int k) {
            int[] count = new int[26];
            int left = 0, maxFreq = 0, best = 0;
            for (int right = 0; right < s.length(); right++) {
                maxFreq = Math.max(maxFreq, ++count[s.charAt(right) - 'A']);
                while (right - left + 1 - maxFreq > k) {   // more than k letters would need changing
                    count[s.charAt(left) - 'A']--;
                    left++;
                }
                best = Math.max(best, right - left + 1);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int characterReplacement(string s, int k) {
            vector<int> count(26, 0);
            int left = 0, maxFreq = 0, best = 0;
            for (int right = 0; right < static_cast<int>(s.size()); right++) {
                maxFreq = max(maxFreq, ++count[s[right] - 'A']);
                while (right - left + 1 - maxFreq > k) {   // more than k letters would need changing
                    count[s[left] - 'A']--;
                    left++;
                }
                best = max(best, right - left + 1);
            }
            return best;
        }
    };

    Python

    class Solution:
        def characterReplacement(self, s: str, k: int) -> int:
            count = [0] * 26
            left = max_freq = best = 0
            for right, c in enumerate(s):
                count[ord(c) - 65] += 1
                max_freq = max(max_freq, count[ord(c) - 65])
                while right - left + 1 - max_freq > k:     # more than k letters would need changing
                    count[ord(s[left]) - 65] -= 1
                    left += 1
                best = max(best, right - left + 1)
            return best

    Common mistakes

    • Recomputing the top count over all 26 letters every step. It is correct, just slower (O(26·n)).
    • Comparing length - maxFreq with k using ≥ instead of >, which rejects windows that need exactly k changes.
    • Thinking the stale maxFreq is a bug and "fixing" it in a way that shrinks the window too much.

    Similar problems