Longest Repeating Character Replacement
Difficulty: Medium · Pattern: Sliding Window · LeetCode #424
s contains uppercase English letters. You may change at most k characters to any other uppercase letter. Return the length of the longest substring you can make consist of a single repeated letter.
Examples
text
s = "ABAB", k = 2 → 4 (change both B's)
s = "AABABBA", k = 1 → 4 ("AABA" → "AAAA")Hints
- In any window, the cheapest fix is to keep the most frequent letter and change the rest.
- A window is valid when
windowLength − maxCount ≤ k. maxCountnever needs to decrease: a smaller max can't produce a longer valid window.
Approach
Slide a window, tracking letter counts and maxf, the highest count seen in any window. If (r − l + 1) − maxf > k, the window needs too many changes, so slide l forward by one (the window size never shrinks, it only shifts).
Why not recompute maxf when shrinking? The answer only improves when a window with a larger maxf appears, so a stale (too high) maxf only keeps the window at its best size so far. The final answer is the largest valid window seen.
Complexity
Time: O(n). Space: O(26).
Python solution
def characterReplacement(s, k):
count = {}
l = maxf = best = 0
for r, c in enumerate(s):
count[c] = count.get(c, 0) + 1
maxf = max(maxf, count[c])
if (r - l + 1) - maxf > k:
count[s[l]] -= 1
l += 1
best = max(best, r - l + 1)
return bestJavaScript solution
function characterReplacement(s, k) {
const count = new Map();
let l = 0, maxf = 0, best = 0;
for (let r = 0; r < s.length; r++) {
count.set(s[r], (count.get(s[r]) || 0) + 1);
maxf = Math.max(maxf, count.get(s[r]));
if (r - l + 1 - maxf > k) { count.set(s[l], count.get(s[l]) - 1); l++; }
best = Math.max(best, r - l + 1);
}
return best;
}