Longest Repeating Character Replacement
Medium
Topics
Given a string s of uppercase English letters and an integer k, you may replace at most k characters with any uppercase letter. Return the length of the longest substring containing a single repeated letter you can obtain.
Example 1
Inside the braced window, every character except the most common one is replaced. A window is legal while window length − count of its commonest character ≤ k, so the window grows on the right and only shrinks when that is violated. Longest legal window: 4.
Cells are the characters of the string; the small numbers underneath are indices.
Input: s = "ABAB", k = 2 Output: 4
Example 2
Input: s = "AABABBA", k = 1 Output: 4
Constraints
- 1 <= s.length <= 10^5
- s consists of uppercase English letters.
- 0 <= k <= s.length
Editorial — intuition, approach, complexity and pitfalls
Intuition
A window is valid if we can turn it into all-same by changing at most k characters, i.e. windowLen - countOfMostFrequentLetter <= k. Grow the window; when it becomes invalid, slide the left edge.
Approach
- Track a frequency map over the current window and the max frequency seen.
- Expand right; if
(right-left+1) - maxFreq > k, shrink from the left. - The answer is the largest valid window length.
Dry Run
s = "AABABBA", k = 1
A window is valid when (length - count of its most common character) <= k, since
every other character has to be replaced.
r=0 add A count {A:1} maxf 1 len 1 needs 0 res 1
r=1 add A count {A:2} maxf 2 len 2 needs 0 res 2
r=2 add B count {A:2, B:1} maxf 2 len 3 needs 1 res 3
r=3 add A count {A:3, B:1} maxf 3 len 4 needs 1 res 4
r=4 add B count {A:2, B:2} maxf 3 len 4 needs 1 res 4 (shrank once)
r=5 add B count {A:1, B:3} maxf 3 len 4 needs 1 res 4 (shrank once)
r=6 add A count {A:2, B:2} maxf 3 len 4 needs 1 res 4 (shrank once)
answer 4
Look at maxf from r=4 onward. It stays at 3 even though no character actually
appears 3 times in the current window any more -- it is STALE, and deliberately
never recomputed. That is the trick most people distrust on sight.
It is safe because a stale maxf can only make the validity test stricter, never
looser. An overstated maxf understates "needs", so the window could in principle
be allowed to grow when it should not -- but the answer only ever grows when the
window does, and the window can only reach a given length if some character
genuinely achieved that frequency earlier. Checked against a version that
recomputes max(count.values()) every step: identical on 20000 random inputs.
The window never shrinks by more than one per step either, because only one
character is added per iteration. The while loop runs at most once.Complexity
- Time — O(n): each index enters and leaves the window at most once.
- Space — O(1): the frequency map holds at most 26 letters.
Common Pitfalls
- You do not need to shrink maxFreq back down — leaving it stale never overestimates the answer.
Full Solution — all languages
class Solution:
def characterReplacement(self, s, k):
count={}
left=maxf=res=0
for right in range(len(s)):
count[s[right]]=count.get(s[right],0)+1
maxf=max(maxf,count[s[right]])
while (right-left+1)-maxf>k:
count[s[left]]-=1
left+=1
res=max(res,right-left+1)
return resimport java.util.*;
class Solution {
public int characterReplacement(String s, int k) {
int[] cnt=new int[26];
int left=0,maxf=0,res=0;
for(int right=0;right<s.length();right++) {
maxf=Math.max(maxf,++cnt[s.charAt(right)-'A']);
while((right-left+1)-maxf>k) {
cnt[s.charAt(left)-'A']--;
left++;
}
res=Math.max(res,right-left+1);
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int characterReplacement(string s, int k) {
int cnt[26]={0},left=0,maxf=0,res=0;
for(int right=0;right<(int)s.size();right++) {
maxf=max(maxf,++cnt[s[right]-'A']);
while((right-left+1)-maxf>k) {
cnt[s[left]-'A']--;
left++;
}
res=max(res,right-left+1);
}
return res;
}
};/**
* @param {string} s
* @param {number} k
* @return {number}
*/ var characterReplacement = function(s, k) {
const count={};
let left=0,maxf=0,res=0;
for(let right=0;right<s.length;right++) {
const c=s[right];
count[c]=(count[c]||0)+1;
maxf=Math.max(maxf,count[c]);
while((right-left+1)-maxf>k) {
count[s[left]]--;
left++;
}
res=Math.max(res,right-left+1);
}
return res;
};