CodeArchon

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
0
A
1
B
2
A
3
B
4
B
5
A
6
Mapcounts
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.

1def flexible_flag_repaint(s: str, k: int) -> int:
2 count: dict[str, int] = {}
3 lo = max_freq = best = 0
4 for hi, c in enumerate(s):
5 count[c] = count.get(c, 0) + 1
6 max_freq = max(max_freq, count[c])
7 while hi - lo + 1 - max_freq > k:
8 count[s[lo]] -= 1
9 lo += 1
10 best = max(best, hi - lo + 1)
11 return best
Variables
k=1
lo=0
maxFreq=0
best=0

How to think about it

  1. `len − maxFreq` = number of non-dominant characters we'd need to repaint.
  2. If that exceeds k, the window is infeasible — slide lo forward.
  3. maxFreq is only tracked monotonically — we never decrease it on shrink; it's still an upper bound on the best achievable window length.
  4. 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 14
{"text":"AABABBA","k":1,"values":["A","A","B","A","B","B","A"]}

Repaint one char → "AAAA" or "BBBB".

Example 24
{"text":"ABAB","k":2,"values":["A","B","A","B"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed