Longest Repeating Character Replacement: the idea to remember.
Find the longest uppercase English substring that can become one repeated character using at most k replacements.
The core insight
A window needs length minus its largest character count replacements. Track a historical maximum frequency for a linear scan.
Why it works
The historical maximum can delay shrinking, but cannot create a larger best length without sufficient frequency having existed in an earlier window.
The mistake to avoid
With a historical maximum the current window need not be valid; use it for the maximum length, not to return a valid substring.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int characterReplacement(String s, int k) {
int[] count = new int[26];
int left = 0, maxCount = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
maxCount = Math.max(maxCount, ++count[s.charAt(right) - 'A']);
while (right - left + 1 - maxCount > k) {
count[s.charAt(left++) - 'A']--;
}
best = Math.max(best, right - left + 1);
}
return best;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.