Longest Run After k Replacements

medium
Unit 10 · Sliding Windows0/3 to milestone

You may change up to k characters of a string. What's the longest substring you can make consist of one repeated character? ("AABABBA" with k = 1 → "AABA" becomes "AAAA", so 4.)

Implement longest_after_replacements(s, k) in O(n) with a sliding window: track character counts in the window and the maximum count seen. The window is valid while window_length - max_count <= k; when it isn't, shrink it from the left. (A neat detail: max_count never has to decrease, because a smaller value can't produce a longer answer.)

Also implement best_window(s, k): the (start, end) half-open indices of one longest valid window (the leftmost one).

#sliding-window#strings2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Longest Run After k Replacements · TechGradify