Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a string s of uppercase English letters and an integer k. You may pick at most k positions and change each one to any uppercase letter. Afterwards, what's the longest substring (block of consecutive characters) made of one repeated letter? Return its length.
Constraints that matter: s has up to 10⁵ characters, and 0 ≤ k ≤ len(s).
Example: s = "AABABBA", k = 1 → 4. Change the A at index 3 to B and you get "AABBBBA", which contains "BBBB". You could also change the B at index 2 to get "AAAA", which is also 4.
Start with brute force
For every substring, count its letters. It can be made uniform if length − (count of the most common letter) ≤ k. Keep the longest such substring.
With counts updated as the end moves, that's O(n²) substrings with O(26) work each. For n = 10⁵ that's about 5·10⁹ substrings, which is too slow.
Building the intuition
First, a fixed window. Say you have "AABA" and k = 1. Which letter should everything become? The most common one, A, so you only repaint the minority. The cost is length − maxCount = 4 − 3 = 1. That's within budget, so the window is valid.
So the invariant is: window length − count of its most common letter ≤ k.
Next, notice that if a window is valid, every smaller window inside it is valid too, because removing a letter never raises the repaint cost. That's exactly the property that lets the variable window from Longest Substring Without Repeating Characters work. Grow right. If the window breaks, shrink from left until it's fixed. Record the length.
To check the invariant you need the most common letter's count. You can keep count[26] and take its max each step. That's 26 work per step, so O(26n), which is already fast enough.
The famous shortcut
You can avoid that scan. Keep max_freq, the highest count any letter has reached in any window so far, and never lower it, even when the true maximum drops after a shrink.
Why is a too-high max_freq harmless? The answer only gets bigger when you find a window with length = max_freq + k for a bigger max_freq. While max_freq is stale, the condition length − max_freq > k makes the window shrink by exactly one each time it grows by one. So it slides along at its current length, and it never records anything longer than best. The moment a letter's real count beats the old max_freq, the window can grow again. You might report a stale window at the same length as best, but never a wrong, longer one.
The optimal approach
- Set
count = [0] * 26,left = 0,max_freq = 0andbest = 0. - For each
right:- increase
count[s[right]], and setmax_freq = max(max_freq, count[s[right]]); - while
(right − left + 1) − max_freq > k, decreasecount[s[left]]and doleft += 1; best = max(best, right − left + 1).
- increase
- Return
best.
The subtle detail: with the never-lowered max_freq, the while loop runs at most once per step. Before you added s[right] the window satisfied the invariant, and adding one character breaks it by at most one. If that feels too clever, recomputing max(count) each step is also correct and still linear. Say so in the interview.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
count = [0] * 26 # letter counts inside s[left..right]
left = 0
max_freq = 0 # highest count any letter has reached in a window
best = 0
for right, c in enumerate(s):
count[ord(c) - ord('A')] += 1
max_freq = max(max_freq, count[ord(c) - ord('A')])
# Letters to repaint = window length - most common letter.
# More than k? Shrink. max_freq is never lowered: a stale value only
# keeps the window at its best size so far, which can't beat best.
while (right - left + 1) - max_freq > k:
count[ord(s[left]) - ord('A')] -= 1
left += 1
best = max(best, right - left + 1)
return bestclass Solution {
public:
int characterReplacement(string s, int k) {
int count[26] = {0}; // letter counts inside s[left..right]
int left = 0;
int maxFreq = 0; // highest count any letter has reached in a window
int best = 0;
for (int right = 0; right < (int)s.size(); right++) {
count[s[right] - 'A']++;
maxFreq = max(maxFreq, count[s[right] - 'A']);
// Letters to repaint = window length - most common letter.
// More than k? Shrink. maxFreq is never lowered: a stale value only
// keeps the window at its best size so far, which can't beat best.
while ((right - left + 1) - maxFreq > k) {
count[s[left] - 'A']--;
left++;
}
best = max(best, right - left + 1);
}
return best;
}
};class Solution {
public int characterReplacement(String s, int k) {
int[] count = new int[26]; // letter counts inside s[left..right]
int left = 0;
int maxFreq = 0; // highest count any letter has reached in a window
int best = 0;
for (int right = 0; right < s.length(); right++) {
count[s.charAt(right) - 'A']++;
maxFreq = Math.max(maxFreq, count[s.charAt(right) - 'A']);
// Letters to repaint = window length - most common letter.
// More than k? Shrink. maxFreq is never lowered: a stale value only
// keeps the window at its best size so far, which can't beat best.
while ((right - left + 1) - maxFreq > k) {
count[s.charAt(left) - 'A']--;
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
}/**
* @param {string} s
* @param {number} k
* @return {number}
*/
var characterReplacement = function (s, k) {
const A = "A".charCodeAt(0);
const count = new Array(26).fill(0); // letter counts inside s[left..right]
let left = 0;
let maxFreq = 0; // highest count any letter has reached in a window
let best = 0;
for (let right = 0; right < s.length; right++) {
const c = s.charCodeAt(right) - A;
count[c]++;
maxFreq = Math.max(maxFreq, count[c]);
// Letters to repaint = window length - most common letter.
// More than k? Shrink. maxFreq is never lowered: a stale value only
// keeps the window at its best size so far, which can't beat best.
while (right - left + 1 - maxFreq > k) {
count[s.charCodeAt(left) - A]--;
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
};Dry run
s = "AABABBA", k = 1
| right | char | Counts (A, B) after adding | max_freq | Length − max_freq | Shrink? | Window | best |
|---|---|---|---|---|---|---|---|
| 0 | A | 1, 0 | 1 | 1 − 1 = 0 | no | A | 1 |
| 1 | A | 2, 0 | 2 | 0 | no | AA | 2 |
| 2 | B | 2, 1 | 2 | 1 | no | AAB | 3 |
| 3 | A | 3, 1 | 3 | 1 | no | AABA | 4 |
| 4 | B | 3, 2 | 3 | 5 − 3 = 2 | drop A | ABAB | 4 |
| 5 | B | 2, 3 | 3 | 2 | drop A | BABB | 4 |
| 6 | A | 2, 3 | 3 | 2 | drop B | ABBA | 4 |
The last row shows the stale max_freq. "ABBA" really needs 2 changes, but the window only slid along at length 4 and never beat best. The answer is 4.
Complexity
- Time: O(n).
rightandlefteach move at most n times, and each step is O(1) (O(26) per step if you recompute the max instead). - Space: O(1). A fixed array of 26 counts.
Edge cases and traps
k = 0. Then it's just the longest run of one letter."ABBB"→ 3.k ≥ n. You can repaint everything, so the answer is n.- Counting the wrong letter's frequency. The cost uses the window's most common letter, not
s[right]ors[left]. - Trying each target letter separately. Running the window 26 times, once per letter, is correct and O(26n). It's fine, just slower to write.
- Index math. Use
ord(c) − ord('A')for uppercase. The constraints say uppercase only.
Say it in the interview
"A window can be made all one letter with length minus its most-common-letter count changes, so it's valid when that's at most k. Shrinking a valid window keeps it valid, so I use a sliding window. I grow right, keep 26 counts, and shrink from the left while the cost goes over k, recording the best length. I keep max frequency as the best seen so far without lowering it. A stale value only makes the window slide at its current best length, so it can't produce a wrong answer. That's O(n) time and O(1) space."
Follow-ups interviewers ask
- "Why is never lowering
max_freqsafe?" The answer only grows when some letter's count reaches a new high. Until then, the stale value keeps the window length fixed atbest, so nothing longer is ever recorded wrongly. - "Binary-array version: flip at most k zeros to ones?" That's Max Consecutive Ones III. It's the same window, where the invariant is "zeros in the window ≤ k".
- "Return the substring?" Store
leftwheneverbestimproves, and slices[left : left + best].
Practise the same idea
This is Day 25 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free