Problem
Given a string of uppercase English letters and an integer k, you may replace at most k characters. Return the length of the longest substring that can be made of one repeated letter after those replacements.
Original: LeetCode 424: Longest Repeating Character Replacement.
Examples
Example 1
`s = "ABAB", k = 2``4`Example 2
`s = "AABABBA", k = 1``4`Constraints
1 <= s.length <= 10^5sconsists of only uppercase English letters.0 <= k <= s.length
Hints
Hint 1
You choose one target letter for the whole substring and change the other letters into it, up to k times. Different windows may choose different target letters. The result is a length.
Hint 2
A variable-size window whose validity rule is
window length − max frequency <= k. Growing can only raise the number of replacements needed.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Try every substring, count letters, and test whether length − max count <= k: O(n²).
Optimal. Count letters in the window and keep the highest frequency seen as the window grows. If hi - lo + 1 - maxFreq exceeds k, advance lo and decrement that letter. The longest window that passes the test is the answer. You do not have to recompute maxFreq after every shrink: a stale, slightly high frequency can only make you shrink sooner, and you only care about the maximum length.
Alternative. Recompute the max frequency after every shrink for a slightly more obvious version, still O(n) with a 26-letter alphabet.
Complexity
- Time
- O(n)
O(n) time, O(1) extra space for the 26-letter counts.
- Space
- O(1)
Code
public class LongestRepeatingCharacterReplacement {
static int characterReplacement(String s, int k) {
var count = new int[26];
int lo = 0, best = 0, maxFreq = 0;
for (int hi = 0; hi < s.length(); hi++) {
maxFreq = Math.max(maxFreq, ++count[s.charAt(hi) - 'A']);
while (hi - lo + 1 - maxFreq > k) {
count[s.charAt(lo++) - 'A']--;
}
best = Math.max(best, hi - lo + 1);
}
return best;
}
public static void main(String[] args) {
System.out.println(characterReplacement("ABAB", 2)); // 4
System.out.println(characterReplacement("AABABBA", 1)); // 4
}
}Edge cases
- k large enough to cover the whole string, as in "ABAB" with k = 2, returns 4.
- A window that is not a prefix, as in "AABABBA" with k = 1, whose best length is 4.
Follow-ups
- Max Consecutive Ones III is the same idea on a binary array: the 'most frequent letter' is 1, and k is how many zeros you may flip.
Interview script
"A window can be made uniform when its length minus the count of its most common letter is at most k. I grow the window, shrink from the left when that budget is exceeded, and keep the longest valid length. Linear time."
Source: LeetCode 424: Longest Repeating Character Replacement