Longest Repeating Character Replacement
MediumNeetCode 150 Sliding WindowCREDPocket GemsProblem
You are given a string s of capital letters and an integer k. In one move you may
change any single character to any other capital letter. You may make at most k moves.
Return the length of the longest contiguous piece of s that can be turned into one repeated
letter using those moves.
Constraints
- 1 ≤ s.length ≤ 10⁵
- s has only capital English letters
- 0 ≤ k ≤ s.length
Examples: pick one to animate
Solutions
Time: right visits each index once and left only moves forward, so there are at most 2n pointer moves, each with O(1) work.
Space: The count table has 26 slots no matter how long s is.
A window is good when size − (count of its most common letter) ≤ k: the rest are the letters
we replace. Slide right; when the window is bad, slide left by one so the window never shrinks.
maxFreq is never lowered, because only a higher frequency can produce a bigger answer.