Longest Repeating Character Replacement
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
You're given a string s of uppercase English letters and an integer k. You may replace up to k characters of s with any other uppercase letter.
Return the length of the longest substring that can be made of a single repeated letter.
Understand the problem
- You may change at most
kletters (you can also change fewer, or none). - After changing, look for the longest piece of neighbouring letters that are all the same, like
"BBBB". - You return only the length.
Another way to say it: find the longest piece of s that you could turn into one repeated letter using at most k changes.
Example 1
Input: s = "ABAB", k = 2
Output: 4Change both As to B → "BBBB", length 4. (Changing both Bs to A works too.)
Example 2
Input: s = "AABABBA", k = 1
Output: 4Change the A at index 3 to B → "AABBBBA", which contains "BBBB", length 4. No single change gives 5 in a row.
Example 3
Input: s = "AAAA", k = 0
Output: 4No changes needed: it's already all A.
Constraints
1 <= s.length <= 10^5scontains uppercase English letters only.0 <= k <= s.length
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Slide a window over the string, and keep it only as wide as can be turned into one letter: its length minus the count of its most common letter must be at most k.
The naive approach (and why it's slow)
For every substring, count its letters, find the most common one, and check whether the rest (the letters you'd change) is at most k. There are about n²/2 substrings, so this is at least O(n²). For 100,000 letters, billions of steps.
The key insight
First, the rule for one window. To turn a window into a single letter with the fewest changes, keep its most common letter and change the rest:
window "AABAB": A appears 3 times, B appears 2 times
keep the A's, change the 2 B's → "AAAAA"
changes needed = length - maxCount = 5 - 3 = 2So a window is valid when length - maxCount <= k.
Second, slide instead of restarting. Use a sliding window with a letter count (a hash map or a 26-slot array):
- Add
s[right]to the counts, updatemaxCount. - If the window is invalid, drop
s[left]from the counts and moveleftforward. - Record the window length.
Step by step
s = "AABABBA", k = 1:
right | Letter | Window | Counts | maxCount | Changes needed (len - max) | Valid? | Action | Best |
|---|---|---|---|---|---|---|---|---|
| 0 | A | A | A:1 | 1 | 0 | ✅ | 1 | |
| 1 | A | AA | A:2 | 2 | 0 | ✅ | 2 | |
| 2 | B | AAB | A:2 B:1 | 2 | 1 | ✅ | 3 | |
| 3 | A | AABA | A:3 B:1 | 3 | 1 | ✅ | 4 | |
| 4 | B | AABAB | A:3 B:2 | 3 | 2 | ❌ | drop A, left++ → ABAB | 4 |
| 5 | B | ABABB | A:2 B:3 | 3 | 2 | ❌ | drop A, left++ → BABB | 4 |
| 6 | A | BABBA | A:2 B:3 | 3 | 2 | ❌ | drop B, left++ → ABBA | 4 |
Answer: 4.
Why maxCount never has to go down
When we shrink the window, the real most-common count might drop, but the code leaves maxCount alone. That looks like a bug, but it's safe:
- The answer can only get bigger if some window has a bigger
maxCountthan we've ever seen (a longer valid window needs more copies of one letter). - A stale, too-high
maxCountcan only keep the window at the size of the best answer so far. It never makes us report a window longer than a real one.
Also notice the window never shrinks by more than one per step: it either grows or slides. That's why "drop one, move left once" is enough instead of a while loop (the reference code still uses while, which works the same way).
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). Each letter enters the window once and leaves at most once.
- Memory: O(1). At most 26 letter counts.
Common mistakes
- Trying every target letter separately. Running the window 26 times (once per letter) works and is O(26 · n), but it's more code than needed.
- Recomputing
maxCountby scanning the counts after every shrink. Correct, but unnecessary (see above). - Forgetting to decrement the count of the letter that leaves on the left.
Going deeper
The key move in this problem is turning "can this window be fixed?" into a single number check (length - maxCount <= k). Most sliding window problems hinge on finding that kind of cheap "is the window valid?" test.
Reference solution
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
export default function characterReplacement(s, k) {
// letter -> how many times it appears in the window s[left..right]
const counts = new Map()
let left = 0
let maxCount = 0 // the highest count of a single letter we've seen in a window
let best = 0
for (let right = 0; right < s.length; right++) {
// Add the new letter to the window.
const count = (counts.get(s[right]) ?? 0) + 1
counts.set(s[right], count)
maxCount = Math.max(maxCount, count)
// Letters to change = window length - most common letter. Too many? Shrink.
// (maxCount is never lowered: a stale value can't make us report a too-long window.)
while (right - left + 1 - maxCount > k) {
counts.set(s[left], counts.get(s[left]) - 1)
left++
}
best = Math.max(best, right - left + 1)
}
return best
}export default function characterReplacement(s: string, k: number): number {
// letter -> how many times it appears in the window s[left..right]
const counts = new Map<string, number>()
let left = 0
let maxCount = 0 // the highest count of a single letter we've seen in a window
let best = 0
for (let right = 0; right < s.length; right++) {
// Add the new letter to the window.
const count = (counts.get(s[right]) ?? 0) + 1
counts.set(s[right], count)
maxCount = Math.max(maxCount, count)
// Letters to change = window length - most common letter. Too many? Shrink.
// (maxCount is never lowered: a stale value can't make us report a too-long window.)
while (right - left + 1 - maxCount > k) {
counts.set(s[left], (counts.get(s[left]) ?? 0) - 1)
left++
}
best = Math.max(best, right - left + 1)
}
return best
}from collections import defaultdict
def character_replacement(s: str, k: int) -> int:
# letter -> how many times it appears in the window s[left..right]
counts = defaultdict(int)
left = 0
max_count = 0 # the highest count of a single letter we've seen in a window
best = 0
for right, char in enumerate(s):
# Add the new letter to the window.
counts[char] += 1
max_count = max(max_count, counts[char])
# Letters to change = window length - most common letter. Too many? Shrink.
# (max_count is never lowered: a stale value can't make us report a too-long window.)
while right - left + 1 - max_count > k:
counts[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return best