Full answer
Problem
Given an uppercase string s and an integer k, you may replace at most k characters with any letter. Return the length of the longest substring that can be made of one repeated letter.
Example: "AABABBA", k = 1 gives 4 (change one letter in "AABA" to get "AAAA").
Constraints: 0 <= len(s) <= 10^5, 0 <= k <= len(s).
Brute force
For each substring, compute its most frequent letter count and check length - max_count <= k: O(n^2 x 26) or worse.
Optimal approach
Keep counts for the window, left, and max_count.
For each right:
- Increment
counts[s[right]];max_count = max(max_count, counts[s[right]]). - While
(right - left + 1) - max_count > k, decrementcounts[s[left]]and moveleftright. - Update
best.
Why it works
The cheapest way to make a window uniform is to keep its most frequent letter and change the rest, so length - max_count changes are needed. The window is valid exactly when that number is at most k.
Why max_count need not decrease when shrinking: the answer only improves if some window has a larger max_count than any seen before. A stale, too-large max_count can only keep the window at its current best length, never report a length that was not achievable earlier, because best was already set to that length when max_count was accurate. This makes the loop O(n) without recounting.
Complexity
O(n) time, O(26) = O(1) space.
Code
def character_replacement(s, k):
"""Longest substring that can become one repeated letter with at most k changes."""
counts = {}
left = max_count = best = 0
for right, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1
max_count = max(max_count, counts[ch])
while (right - left + 1) - max_count > k: # too many letters to change
counts[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return best
def brute(s, k):
best = 0
for i in range(len(s)):
for j in range(i, len(s)):
window = s[i:j + 1]
if len(window) - max(window.count(c) for c in set(window)) <= k:
best = max(best, len(window))
return best
if __name__ == "__main__":
for f in (character_replacement, brute):
assert f("ABAB", 2) == 4
assert f("AABABBA", 1) == 4
assert f("", 3) == 0
assert f("AAAA", 0) == 4
assert f("ABCDE", 0) == 1
assert f("ABCDE", 10) == 5
print("all tests passed")Save as a24_char_replacement.py and run python3 a24_char_replacement.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty string returns 0. k = 0 gives the longest run of one letter. k >= len(s) gives len(s). All letters different with small k gives k + 1 (capped at length).
Pattern
Variable sliding window with a "cost to fix" condition. Related: longest subarray of 1s after flipping at most k zeros (count zeros instead of non-majority letters).
def character_replacement(s, k):
"""Longest substring that can become one repeated letter with at most k changes."""
counts = {}
left = max_count = best = 0
for right, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1
max_count = max(max_count, counts[ch])
while (right - left + 1) - max_count > k: # too many letters to change
counts[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return best
def brute(s, k):
best = 0
for i in range(len(s)):
for j in range(i, len(s)):
window = s[i:j + 1]
if len(window) - max(window.count(c) for c in set(window)) <= k:
best = max(best, len(window))
return best
if __name__ == "__main__":
for f in (character_replacement, brute):
assert f("ABAB", 2) == 4
assert f("AABABBA", 1) == 4
assert f("", 3) == 0
assert f("AAAA", 0) == 4
assert f("ABCDE", 0) == 1
assert f("ABCDE", 10) == 5
print("all tests passed")Variable window that shrinks while length - max_count > k; a brute force is tested on the same inputs.
Complexity
Time: O(n). Space: O(1) (at most 26 counts). max_count is never decreased; this is safe because only a larger max_count can improve the answer.
By level
Fresher: Explains the validity condition and implements the window, recomputing the max count if needed. Should trace the window on "AABABBA" with k = 1.
Mid: Uses the non-decreasing max_count with a correct justification and solves the flip-zeros variant. Tests k = 0 and k larger than the string.
Senior: Generalises to weighted costs or larger alphabets, discusses when the monotonic trick is valid in other problems, and proves the window invariant carefully. Can explain when a stale maximum would be wrong in other window problems.
Key points
- Window is valid when length - max_count <= k
- Grow right, shrink left while invalid
- Changes needed = letters that are not the majority
- A stale max_count does not produce a wrong answer
- O(n) time
Common mistakes
- Recomputing the maximum count over 26 letters on every shrink without noting the cost
- Shrinking with an if instead of a while in the general template
- Forgetting the k >= length case
- Thinking a stale max_count gives wrong answers without reasoning about it
Follow-ups
- How would you solve max consecutive ones with k flips?
- Can you return the substring itself?
- What if replacements have different costs per letter?
Tips
- Derive length - max_count before coding
- Explain the stale max_count argument briefly
- Test k = 0
Evaluation rubric
- Correct condition and window logic
- Correct O(n) reasoning
- Handles edge cases
- Explains the max_count subtlety or recomputes safely