Longest Repeating Character Replacement

MediumSliding Window · Majority Count🧩 Sliding WindowLeetCode #424 ↗Updated

Problem

You get a string s of uppercase English letters and a budget k. You may overwrite at most k characters with any letter you like. Return the length of the longest contiguous block that can be made to consist of a single repeated letter.
Inputs = "ABAB", k = 2Output4 (rewrite both B's)
Inputs = "AABABBA", k = 1Output4 (e.g. "AABA" → "AAAA")
Inputs = "ABCD", k = 0Output1

1 ≤ n ≤ 105  ·  s has uppercase letters only  ·  0 ≤ k ≤ n

Try it yourself

Java
class Solution {
    public int characterReplacement(String s, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A window is fixable iff length - (count of its most common letter) ≤ k. Slide a window; the answer can only grow when that top count grows, so the top count never needs to be decreased.
PatternSliding Window

Instinct Longest, shortest or count of contiguous subarrays/substrings meeting a rule? Grow a window on the right, shrink it on the left, never step back.

Memory hack Move like a caterpillar - the head stretches forward to grab, the tail pulls up only when the body breaks the rule.

Open the Sliding Window guide →

Approaches

Brute ForceEvery Start, Extend with Running Counts

Time O(n2)Space O(1)

For each start i, extend the end j one letter at a time while updating 26 counts and the running maximum count. Whenever (j - i + 1) - maxCount ≤ k, the block can be made uniform by rewriting the minority letters.

Java
public int characterReplacement(String s, int k) {
    int n = s.length(), best = 0;
    for (int i = 0; i < n; i++) {
        int[] count = new int[26];
        int maxCount = 0;
        for (int j = i; j < n; j++) {
            maxCount = Math.max(maxCount, ++count[s.charAt(j) - 'A']);
            if (j - i + 1 - maxCount <= k) best = Math.max(best, j - i + 1);
        }
    }
    return best;
}

Simple and correct, but tries all n2/2 substrings.

At a glance

LevelApproachTimeSpace
Brute ForceEvery Start, Extend with Running CountsO(n2)O(1)
BetterSliding Window, Recompute the MaxO(26 · n)O(1)
OptimalNon-Shrinking Window with Stale MaxO(n)O(1)
Common pitfalls
  • Counting distinct letters instead of length - maxCount as the cost.
  • Believing the stale maxFreq is a bug — it is safe because it never inflates the answer.
  • Moving left without decrementing the count of the letter that leaves the window.
Interview tips
  • Phrase the validity test first: changes needed = length - most frequent count.
  • Present the O(26n) window, then justify the never-decreasing maxFreq trick.
  • Mention the alternative: run a “at most k non-X” window for each letter X.
Pattern
Sliding window with a budget → longest range where the number of “bad” items is at most k.
My notes saved in this browser