Longest Repeating Character Replacement – Solution & Complexity
Solution Walkthrough
Step 1: Define window validity
- A window
s[left..right]can be turned into one repeated character if the number of characters that are not the most frequent letter is at mostk. - In symbols:
(right - left + 1) - max_freq <= k.
- A window
Step 2: Why max_freq only needs to grow
- Expand
rightone step at a time, incrementcounts[s[right]], and updatemax_freq = max(max_freq, counts[s[right]]). - Whenever
(right - left + 1) - max_freq > k, decrementcounts[s[left]]and advanceleftby 1. - Keeping
max_freqas the historical high-water mark is safe because a shorter window or a smallermax_freqcan never beat the best length we have already found.
- Expand
Step 3: Optimal O(n) sliding window
- Single pass over
swith a fixed 26-slot frequency table:O(n)time andO(1)extra space.
- Single pass over
Step 4: Common mistakes
- Assuming the target character must be
s[left]:"ABBB"withk = 2turns'A'into'B', not'B'into'A'. - Re-scanning all 26 counts on every shrink step works in
O(26n)but isn't needed.
- Assuming the target character must be
Part of Blind 75 · NeetCode 150