Longest Repeating Character Replacement (LeetCode 424): Solution and Explanation
You are given a string of uppercase letters and an integer k. You may change at most k characters to any other uppercase letter. Return the length of the longest substring that can be made of a single repeated letter after those changes.
Watch it run step by step
Try your own input and write the code →Intuition
For a fixed substring, the cheapest way to make it uniform is to keep its most common letter and replace everything else. So a window of length len is achievable exactly when len - maxFreq <= k, where maxFreq is the count of its most frequent letter. Checking every substring with that test is O(n²) windows, or O(26 × n²) with counting, which is far too slow for long strings.
The condition behaves nicely for a sliding window. If a window is valid, shrinking it keeps it valid, and if it is invalid, growing it cannot help. So you can extend a right pointer one character at a time and, whenever the window breaks the rule, move the left pointer forward until it is valid again. Every window you record is legal, and you track the longest one.
There is a well known subtlety in how the reference code keeps maxf. It only ever increases, even when the left pointer drops letters that were part of the maximum. That looks like a bug but is not. The answer can only improve when some letter reaches a new, higher frequency, because the window length is bounded by maxf + k. A stale maxf might let the window stay a bit larger than strictly valid, but it never causes the recorded best to exceed a length that was truly achieved earlier, so the result is still correct and you avoid rescanning 26 counts.
Approach: Sliding window with a running max frequency
- Keep a
countdictionary for letters in the window, a left pointerl, the best lengthres, andmaxffor the highest frequency seen. - For each right index
r, incrementcount[s[r]]and updatemaxfwith that new count. - While the window length
r - l + 1minusmaxfexceedsk, decrement the count ofs[l]and movelright. - Update
reswith the current window lengthr - l + 1. - After the loop finishes, return
res.
Step-by-step example
s = "AABABBA", k = 1
- For r = 0 to 2 the window grows to "AAB". A has count 2, so 3 - 2 = 1 replacement is allowed, and
resbecomes 3. - At r = 3 the window is "AABA" with A at 3, which needs one replacement.
resbecomes 4. - At r = 4 the window "AABAB" needs 5 - 3 = 2 replacements, which is too many. Dropping the first A makes it "ABAB", which is valid with length 4.
- At r = 5, B reaches 3 but
maxfstays 3. The window "ABABB" needs 2 replacements, so the left A is dropped, leaving "BABB" with length 4. - At r = 6 the window "BABBA" needs 2 replacements, so the left B is dropped and the window becomes "ABBA" with length 4.
- The loop ends and returns 4, for example by turning "AABA" into "AAAA".
Code: Python, Java, C++
1class Solution:
2 def characterReplacement(self, s: str, k: int) -> int:
3 count = {}
4 res = 0
5 l = 0
6 maxf = 0
7
8 for r in range(len(s)):
9 count[s[r]] = 1 + count.get(s[r], 0)
10 maxf = max(maxf, count[s[r]])
11
12 while (r - l + 1) - maxf > k:
13 count[s[l]] -= 1
14 l += 1
15 res = max(res, r - l + 1)
16 return res1class Solution {
2 public int characterReplacement(String s, int k) {
3 int[] count = new int[26];
4 int l = 0, maxf = 0, res = 0;
5
6 for (int r = 0; r < s.length(); r++) {
7 count[s.charAt(r) - 'A']++;
8 maxf = Math.max(maxf, count[s.charAt(r) - 'A']);
9
10 while ((r - l + 1) - maxf > k) {
11 count[s.charAt(l) - 'A']--;
12 l++;
13 }
14 res = Math.max(res, r - l + 1);
15 }
16 return res;
17 }
18}1class Solution {
2public:
3 int characterReplacement(string s, int k) {
4 vector<int> count(26);
5 int maxf = 0;
6 int l = 0;
7 int res = 0;
8
9 for (int r = 0; r < s.length(); r++) {
10 count[s[r] - 'A']++;
11 maxf = max(maxf, count[s[r] - 'A']);
12
13 while ((r - l + 1) - maxf > k) {
14 count[s[l] - 'A']--;
15 l++;
16 }
17 res = max(res, r - l + 1);
18 }
19 return res;
20 }
21};Time and space complexity
O(n)
Each index is added once when r passes it and removed at most once when l passes it, so both pointers move at most n steps in total.
O(1)
The count map holds at most 26 uppercase letters no matter how long the string is.
Other approaches
Recompute max frequency from the counts (time O(26 × n), space O(1))
Instead of the monotonic maxf, compute max(count.values()) each time you check the window. It is easier to reason about and still linear for a fixed alphabet, at the cost of a factor of 26.
Window per target letter (time O(26 × n), space O(1))
For each of the 26 letters, run a sliding window that counts how many characters differ from that letter and keeps the count at or below k. Take the best length across all letters.
Common mistakes
- Comparing against
kwith the wrong expression. The number of replacements needed is the window length minusmaxf, not the number of distinct letters. - Trying to decrease
maxfwhen the left pointer moves without recomputing it correctly, which can produce a value lower than the true maximum. - Updating
resbefore shrinking the window, which can record an invalid window length. - Assuming lowercase letters or digits. The constraint says uppercase English letters, which is what keeps the counts bounded.
Frequently asked questions
Why doesn't maxf need to decrease when the window shrinks?
A longer valid window can only appear once some letter's count exceeds the old maxf. Keeping the stale higher value never lets res exceed a length that was actually valid earlier, so the final answer stays correct.
What is the time complexity of Longest Repeating Character Replacement?
It is O(n), since both pointers only move forward through the string. The space is O(1) because the alphabet is limited to 26 letters.
How do you know when the window is invalid?
A window needs length - maxFreq changes to become one letter. When that number is greater than k, the window is invalid and the left edge must move.