Problem
You are given a string
sconsisting of only uppercase English characters and an integerk. You can choose up tokcharacters of the string and replace them with any other uppercase English character.After performing at most
kreplacements, return the length of the longest substring which contains only one distinct character.
Example 1
Input: s = "XYYX", k = 2
Output: 4
Either replace the 'X's with 'Y's, or replace the 'Y's with 'X's.
Example 2
Input: s = "AAABABB", k = 1
Output: 5
Constraints
1 <= len(s) <= 100,0000 <= k <= len(s)sconsists of only uppercase English characters.
Thinking
- Brute force idea: try every substring
s[i..j]; it can be made uniform if the characters that are not its most frequent letter number at mostk. Extendingjwith running counts gives , far too slow for . - Key insight: a window can be made one letter iff
window_len - max_freq <= k(keep the most frequent letter, replace everything else). This check is monotone: growing an invalid window keeps it invalid, shrinking a valid one keeps it valid. So use a sliding window:radds one character per step, and when the window becomes invalid, movelright. - “Longest” means the window never has to shrink: once a window of size
wwas valid, nothing smaller matters. So when it’s invalid, movelby one (slide the window, size unchanged) instead of shrinking until it’s valid. For the same reasonmax_freqnever has to go down whenlmoves: a stale, too-high value can only keep the window from shrinking, and the answer only grows when some letter’s count beats the oldmax_freq, and that new count is always real. - Another way to see it: fix the letter you keep (26 choices). Then it’s “longest window with at most
kcharacters that aren’t the target”, which is Max Consecutive Ones III (#1004). , and nomax_freqsubtlety. - Edge cases to remember:
k = 0(→ the longest run of one letter);k >= len(s)(→len(s)); a single character; all the same letter; all distinct (→min(len(s), k + 1)); the best window is in the middle or at the very end; the best window shows up after a different letter was the most frequent ("ABBBAAAA",k = 1→ 5).
Solution
Approach A — mine: non-shrinking sliding window
Complexity: Time · Space
Correct, and already linear. It uses an if, not a while, so the window never shrinks: on every step it
either grows by one (valid, so max_l becomes its size) or slides right by one (invalid: add s[r], drop s[l]).
That means r - l + 1 == max_l after every step, so the window being checked at r is exactly the
one candidate that could beat the answer. Because max(c_dict.values()) is the real maximum, that check is
exact, and continue is safe: a slid window has the same size as max_l, so there’s nothing to record.
Only polish is left: max(c_dict.values()) rescans up to 26 counts on every character (a running max_freq
makes it ), and Counter is imported but never used.
from collections import Counter # unused
def character_replacement_mine(s: str, k: int) -> int:
c_dict = {}
l = 0
max_l = 0
for r in range(len(s)):
c_dict[s[r]] = 1 + c_dict.get(s[r], 0)
if r - l + 1 - max(c_dict.values()) > k: # max() scans up to 26 counts every step
c_dict[s[l]] -= 1 # slide, don't shrink: the window keeps size max_l
l += 1
continue
max_l = max(max_l, r - l + 1)
return max_l
Approach B — brute force: extend from every start
Complexity: Time · Space
For each start i, extend j while keeping running counts and the running max, and record every valid
window. Obviously correct, so the tests use it as the reference on random strings. Way too slow for .
def character_replacement_brute(s: str, k: int) -> int:
best = 0
for i in range(len(s)):
count = {}
max_freq = 0
for j in range(i, len(s)): # recounts the same characters for every i
count[s[j]] = count.get(s[j], 0) + 1
max_freq = max(max_freq, count[s[j]])
if (j - i + 1) - max_freq <= k:
best = max(best, j - i + 1)
return best
Approach C — fix the target letter (Max Consecutive Ones III, 26 times)
Complexity: Time · Space
For each letter that appears, find the longest window with at most k characters that aren’t that letter
(those are the ones you’d replace). There’s no max_freq here, and the window is always valid, so it’s the easiest
version to prove correct. The price is 26 passes over the string.
def character_replacement_per_letter(s: str, k: int) -> int:
best = 0
for target in set(s):
l = others = 0 # others = characters in the window that aren't target
for r, c in enumerate(s):
others += c != target
while others > k:
others -= s[l] != target
l += 1
best = max(best, r - l + 1)
return best
Approach D — sliding window + running max_freq ✅ best practice
Complexity: Time · Space
The version to remember. Same window as A, but the most common count is updated in when a character
comes in, and it is never decreased when one leaves (see Thinking: a stale value can’t inflate the
answer). Because max_freq only gets bigger, the window is never more than one character over the limit, so the
while runs at most once and works exactly like A’s if. It’s written as while so it reads like every
other sliding window.
def character_replacement(s: str, k: int) -> int:
count = {}
l = max_freq = best = 0
for r, c in enumerate(s):
count[c] = count.get(c, 0) + 1
max_freq = max(max_freq, count[c]) # never decreased: a stale max can't inflate best
while (r - l + 1) - max_freq > k: # more than k to replace: move l (runs at most once)
count[s[l]] -= 1
l += 1
best = max(best, r - l + 1)
return best
Scratch / Experiments
Input: a random string over all 26 letters at the max length with k = 100, so A’s
max(c_dict.values()) really scans 26 counts and C really makes 26 passes. The brute force is and
would take minutes at that size, so it runs on the first 2,000 characters only.
Measured (): running max_freq (D) ~19 ms, mine (A) ~32 ms, fix-the-letter (C) ~300 ms. On the 2,000-character prefix the brute force takes ~217 ms against ~0.37 ms for D (~600× slower). It grows with , so at full size it would take about 2,500× longer, around 9 minutes.
A is only ~1.6× slower than D even though it rescans up to 26 counts every step: max(c_dict.values()) runs in C, so 26 comparisons cost about as much as a couple of Python-level operations. C has the same bound, but its constant is 26 passes of a Python loop, which is why it is ~16× slower. Big-O hides constants, and in Python the constant that matters is how many Python-level steps run per character.
rng = random.Random(0)
s = "".join(rng.choice(string.ascii_uppercase) for _ in range(100_000))
k = 100
small = s[:2_000]
assert character_replacement_mine(s, k) == character_replacement_per_letter(s, k) == character_replacement(s, k)
assert character_replacement_brute(small, k) == character_replacement(small, k)
%timeit character_replacement_mine(s, k)
%timeit character_replacement_per_letter(s, k)
%timeit character_replacement(s, k)
%timeit -n 1 -r 3 character_replacement_brute(small, k)
%timeit character_replacement(small, k)
Takeaways
- Pattern: “longest substring that can be made uniform with ≤ k changes” → sliding window + letter
counts, valid while
window_len - max_freq <= k. More generally: turn the condition into a check that’s to update as the window moves, thenradds,lremoves, and you recordr - l + 1. For longest problems the window can just slide (if, movelby one) instead of shrinking, and helpers likemax_freqnever have to go down. - Mistakes I made:
- First attempt: looped over
land checked onlys[l:]. Those are the substrings that end at the last character, so"AAABA"in example 2 was never tried (it returned 4, not 5). It also rebuilt aCounterfor every start, which is . A substring has two ends; if only one of them moves, you’re missing candidates. - Final version: correct and , but
max(c_dict.values())rescans the counts every step. It’s only cheap because the alphabet has 26 letters. Trackmax_freqas characters come in instead. - Left an unused
from collections import Counter. if+continueis right, but only because the window size equalsmax_lafter every step. Know why it works (or write thewhileversion) so you can defend it in an interview.
- First attempt: looped over
- Related problems: Max Consecutive Ones III (#1004, the one-target-letter version: at most
kzeros); Maximize the Confusion of an Exam (#2024, this problem with only'T'/'F'); Longest Substring Without Repeating Characters (#3, same window shape, condition “no repeats”); Longest Substring with At Most K Distinct Characters (#340, count map + shrink); Permutation in String (#567, fixed-size window with counts); Minimum Window Substring (#76, the shortest version, where the window really must shrink).