mediumSliding WindowAmazonGoogle
Flexible Flag Repaint
A row of colored flags; you may repaint at most k of them. What's the longest run of a single color you can achieve?
Given a string `s` (uppercase letters) and integer `k`, you may replace up to k characters. Return the length of the longest substring containing a single repeated letter after replacements.
Choose approach
A
0A
1B
2A
3B
4B
5A
6Mapcounts
empty
1/16
Narrationstep 1 of 16
Window [lo..hi]. If window length − count of its most-frequent char > k, we'd need more than k repaints. Shrink from lo.
Variables
k=1
lo=0
maxFreq=0
best=0
How to think about it
- `len − maxFreq` = number of non-dominant characters we'd need to repaint.
- If that exceeds k, the window is infeasible — slide lo forward.
- maxFreq is only tracked monotonically — we never decrease it on shrink; it's still an upper bound on the best achievable window length.
- Grow hi one step per iteration; shrink lo until feasible; record best.
Edge cases to catch in interview
- k ≥ n → the whole string works.
- All same letter → length n regardless of k.
- k = 0 → longest run of a single letter.
Examples
Example 1
4{"text":"AABABBA","k":1,"values":["A","A","B","A","B","B","A"]}
Repaint one char → "AAAA" or "BBBB".
Example 2
4{"text":"ABAB","k":2,"values":["A","B","A","B"]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed