Week 2 ยท Sliding Window
Longest Repeating Character Replacement
Find the longest window that can become all one character after at most k replacements.
Medium Sliding Window Week 2 Practice runner
Frame the problem
- The window is contiguous.
- You may replace at most k characters.
- The chosen target character is the most frequent character in the current window.
1. Reveal example inputs and outputs
Example 1
Input:
character_replacement("ABAB", 2) Output:
4 Example 2
Input:
character_replacement("AABABBA", 1) Output:
4 2. Brute force first
For a fixed window, how do you know the minimum replacements needed to make it uniform?
3. Reveal the insight ladder
- Track counts inside the window.
- The needed replacements are window_length - max_frequency.
- If replacements exceed k, shrink from the left.
- The best valid window length is the answer.
4. Dry run before code
- s = AABABBA, k = 1.
- AABA has max frequency 3 and length 4, so one replacement makes it AAAA.
- Longer windows require more than one replacement, so best is 4.
5. Reveal final Python solution
from collections import defaultdict
def character_replacement(s, k):
counts = defaultdict(int)
left = 0
max_count = 0
best = 0
for right, char in enumerate(s):
counts[char] += 1
max_count = max(max_count, counts[char])
while (right - left + 1) - max_count > k:
counts[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return best Complexity: Time O(n), space O(k distinct characters).
Interview narration
- I keep the window valid by measuring how many characters are not the majority.
- The max frequency can be maintained monotonically for this problem.
- Shrinking restores the replacement budget.
Common traps
- Using the number of distinct characters instead of non-majority count.
- Recomputing the entire window too often.
- Forgetting k can be zero.
Follow-up drills
1. Why can max_count be stale?
A stale high max_count may delay shrinking, but it never causes an overestimated answer beyond a window length that was valid when that max_count was observed.
2. How does this differ from longest substring without repeats?
Here repeats are good; the invalid condition is too many non-majority characters, not duplicate existence.
Interactive runner
Write the required Python function. Your code runs locally in this browser. Hints reveal one failing case at a time.