FAANGPrep Sprint
Longest Repeating Character Replacement
Replace characters to get the longest repeating character substring.
Examples
Both changes can go to the same letter: flip the two 'A's to get "BBBB", or the two 'B's to get "AAAA".
With one change, turn the middle 'A' into 'B': "AABBBBA" now holds the run "BBBB", 4 letters long.
Problem Understanding
The input is an uppercase string s and a budget k. One operation overwrites a single character with any other uppercase letter, and you may spend up to k operations.
Goal: return the length of the longest substring that can be made entirely of one repeated letter within that budget.
Algorithm Strategy
We use a Sliding Window to check if a valid window exists. A window (substring) is valid if we can turn it into all same characters using at most k replacements.
Logic:
- Validity Check:
Replacements Needed = Window Length - Count of Most Frequent Char.- If
Replacements Needed <= k, the window is valid. We try to expand it (incrementright). - If
Replacements Needed > k, the window involves too many changes. We perform one shrink step (incrementleft) to try and make it valid again.
- If
- We maintain a frequency map (or array of size 26) to track counts of characters in the current window.
- We keep track of
max_count, the highest count any character has reached in a window so far. It is never decreased, which is why the map is never re-scanned; the section below explains why a stale value still gives the right answer.
Interactive Visualization
k = 1
EMPTY WINDOW
0
1
2
3
4
5
6
Length
—
maxCount
0
Needed
—
Best
0
count
Empty
left at 0, no counts, maxCount 0. At most 1 replacement
Next
Add 'A' at 0: count['A'] = 1
String
k
Watch how the window expands and only shrinks when the number of replacements needed exceeds k.
