Overview
Given a string s consisting of uppercase English letters and an integer k, you can choose any character and change it to any other uppercase letter at most k times. Return the length of the longest substring containing the same letter after performing at most k replacements.
Constraints
1 <= s.length <= 100,000sconsists of only uppercase English letters.0 <= k <= s.length- Must run in O(n) time.
Examples
characterReplacement("ABAB", 2);
// => 4 (replace both A's or both B's → "AAAA" or "BBBB")characterReplacement("AABABBA", 1);
// => 4 (replace one B at index 3 → "AAAAABA", substring "AAAA")Solution
Reveal solution
function characterReplacement(s, k) {
const count = {};
let left = 0, maxFreq = 0, result = 0;
for (let right = 0; right < s.length; right++) {
count[s[right]] = (count[s[right]] || 0) + 1;
maxFreq = Math.max(maxFreq, count[s[right]]);
// window size - most frequent char count = replacements needed
while ((right - left + 1) - maxFreq > k) {
count[s[left]]--;
left++;
}
result = Math.max(result, right - left + 1);
}
return result;
}Sliding window: track the frequency of each character in the window. The number of replacements needed equals window size minus the most frequent character's count. Shrink from the left when replacements exceed k.
Resources
Longest Repeating Substring After Replacements
Overview
Given a string s consisting of uppercase English letters and an integer k, you can choose any character and change it to any other uppercase letter at most k times. Return the length of the longest substring containing the same letter after performing at most k replacements.
Constraints
1 <= s.length <= 100,000sconsists of only uppercase English letters.0 <= k <= s.length- Must run in O(n) time.
Examples
characterReplacement("ABAB", 2);
// => 4 (replace both A's or both B's → "AAAA" or "BBBB")characterReplacement("AABABBA", 1);
// => 4 (replace one B at index 3 → "AAAAABA", substring "AAAA")Solution
Reveal solution
function characterReplacement(s, k) {
const count = {};
let left = 0, maxFreq = 0, result = 0;
for (let right = 0; right < s.length; right++) {
count[s[right]] = (count[s[right]] || 0) + 1;
maxFreq = Math.max(maxFreq, count[s[right]]);
// window size - most frequent char count = replacements needed
while ((right - left + 1) - maxFreq > k) {
count[s[left]]--;
left++;
}
result = Math.max(result, right - left + 1);
}
return result;
}Sliding window: track the frequency of each character in the window. The number of replacements needed equals window size minus the most frequent character's count. Shrink from the left when replacements exceed k.