Longest Repeating Character Replacement
Difficulty: Medium
You're given a string of uppercase letters and a number k. You can change up to k characters to any other letter.
Find the length of the longest substring of one repeated letter (like "AAAA") you can get with at most k changes.
Examples
Input: s = "ABAB", k = 2
Output: 4
Change both "B"s to "A" (or both "A"s to "B") to get "AAAA" or "BBBB", length 4.
Input: s = "AABABBA", k = 1
Output: 4
Change the one "B" inside "ABAB" (positions 1-4, "ABAB") to get "AAAA", giving a substring of length 4. The final "A" can't be joined without another change.
Input: s = "AAAA", k = 0
Output: 4
No changes needed or allowed — the whole string is already one repeated letter.
Constraints
1 <= s.length <= 10^5
s consists of only uppercase English letters.
0 <= k <= s.length
Approach
Brute force checks every substring and counts how many characters differ from its most frequent letter. That's the number of replacements needed; if it's at most k, the substring works. But it re-counts overlapping substrings again and again.
A sliding window does better. Grow it left to right, counting each letter inside. A window of length L needs L - (count of its most frequent letter) replacements, since every other character must change.
While that's <= k, keep growing. When it isn't, shrink from the left by one. The window never needs to shrink below the best length found, so tracking the largest window seen gives the right answer.
Solutions
Brute Force — Check Every Substring
For every substring, count the characters that aren't its most frequent letter (the replacements needed) and check that against k.
function characterReplacement(s, k) {
let best = 0;
for (let start = 0; start < s.length; start++) {
const counts = {};
let maxCount = 0;
for (let end = start; end < s.length; end++) {
counts[s[end]] = (counts[s[end]] || 0) + 1;
maxCount = Math.max(maxCount, counts[s[end]]);
const length = end - start + 1;
const replacementsNeeded = length - maxCount;
if (replacementsNeeded <= k) {
best = Math.max(best, length);
}
}
}
return best;
}Time: O(n²) · Space: O(26) — constant, one count per letter
Optimal — Sliding Window with Max Frequency
Grow the window, tracking letter counts and the highest frequency. If it needs more than k replacements, shrink it from the left by one. The window never shrinks overall, so its final size is the answer.
function characterReplacement(s, k) {
const counts = {};
let left = 0;
let maxCount = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
counts[s[right]] = (counts[s[right]] || 0) + 1;
maxCount = Math.max(maxCount, counts[s[right]]);
const windowLength = right - left + 1;
if (windowLength - maxCount > k) {
counts[s[left]]--;
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}Time: O(n) · Space: O(26) — constant, one count per uppercase letter