Medium dsa sliding-window

Longest Repeating Character Replacement

The 30 second answer

I want the longest substring that can become one repeated letter after at most k replacements. In a window that is valid when length minus the count of its most frequent letter is at most k, I can fill the rest of the window with that letter. I grow the window, track the best letter frequency, shrink from the left when the window needs more than k changes, and keep the longest valid length.

Could you say this in an interview?

Problem Given a string of uppercase English letters and an integer k, you may replace at most k characters. Return the length of the longest substring that can be made of one repeated letter after those replacements. Original: LeetCode 424: Longest Repeating Character Replacement.

Understanding the prompt You choose one target letter for the whole substring and change the other letters into it, up to k times. Different windows may choose different target letters. The result is a length.

Pattern recognition A variable-size window whose validity rule is window length − max frequency <= k. Growing can only raise the number of replacements needed.

Brute force Try every substring, count letters, and test whether length − max count <= k: O(n²).

Optimal Count letters in the window and keep the highest frequency seen as the window grows. If hi - lo + 1 - maxFreq exceeds k, advance lo and decrement that letter. The longest window that passes the test is the answer. You do not have to recompute maxFreq after every shrink: a stale, slightly high frequency can only make you shrink sooner, and you only care about the maximum length.

Alternatives Recompute the max frequency after every shrink for a slightly more obvious version, still O(n) with a 26-letter alphabet.

Java solution

public class LongestRepeatingCharacterReplacement {
    static int characterReplacement(String s, int k) {
        var count = new int[26];
        int lo = 0, best = 0, maxFreq = 0;
        for (int hi = 0; hi < s.length(); hi++) {
            maxFreq = Math.max(maxFreq, ++count[s.charAt(hi) - 'A']);
            while (hi - lo + 1 - maxFreq > k) {
                count[s.charAt(lo++) - 'A']--;
            }
            best = Math.max(best, hi - lo + 1);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(characterReplacement("ABAB", 2));    // 4
        System.out.println(characterReplacement("AABABBA", 1)); // 4
    }
}

Complexity O(n) time, O(1) extra space for the 26-letter counts.

Edge cases

  • k large enough to cover the whole string, as in "ABAB" with k = 2, returns 4.
  • A window that is not a prefix, as in "AABABBA" with k = 1, whose best length is 4.

Follow-ups

  • Max Consecutive Ones III is the same idea on a binary array: the 'most frequent letter' is 1, and k is how many zeros you may flip.

Tests "ABAB" with k=2 returns 4. "AABABBA" with k=1 returns 4.

How to say it in the interview "A window can be made uniform when its length minus the count of its most common letter is at most k. I grow the window, shrink from the left when that budget is exceeded, and keep the longest valid length. Linear time."

Sources (1)
  1. LeetCode 424: Longest Repeating Character Replacementleetcode.com