Longest Repeated-Letter Block With a Limited Rewrite Budget
StringsAuto-graded · 26 test casesLast updated
Find the longest block of identical letters obtainable by rewriting at most k characters, testing sliding-window reasoning on majority counts for strings up to 100,000 characters.
You are given a string text made of uppercase English letters and a non-negative integer budget. In one rewrite you pick a single position in text and replace its letter with any uppercase letter. You may perform at most budget rewrites in total.
After rewriting, look for a contiguous block of the string in which every character is the same letter. Return the greatest length such a block can have, taking the best choice of rewrites.
Rules
- A block is a contiguous, non-empty part of
text. - Rewrites happen in place, so the string length never changes.
- Using fewer than
budgetrewrites, or none at all, is allowed. - The answer is the maximum block length over every allowed way of using at most
budgetrewrites.
Constraints
1 <= len(text) <= 10^5textcontains only the uppercase letters'A'to'Z'.0 <= budget <= len(text)
Examples
Example 1
Input: longest_block_with_rewrites('ABAB', 2)
Output: 4
Example 2
Input: longest_block_with_rewrites('AABABBA', 1)
Output: 4
Example 3
Input: longest_block_with_rewrites('BAAAB', 0)
Output: 3
Hints
Hint 1
Fix a contiguous window. Which letter should it be turned into, and how many rewrites does that take in terms of the window length and the letter counts?
Hint 2
A window is feasible exactly when its length minus the count of its most frequent letter is at most the budget. Use two pointers and keep letter counts for the current window.
Hint 3
You only need the window to grow when a better count appears. Try keeping the largest single-letter count seen so far without ever lowering it, and slide the window by one step instead of shrinking it in a loop.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A window can be turned into one repeated letter with at most budget rewrites exactly when
window length - (count of its most common letter) <= budget
The cheapest plan keeps the most common letter and rewrites everything else.
This suggests a sliding window over the string:
- Move the right end one character at a time and update the letter counts.
- Track
max_freq, the largest single-letter count seen in any window so far. It is never decreased, even when characters leave the window. - If
window length - max_freq > budget, advance the left end by exactly one position (anif, not awhile). The window then keeps its previous length, so it slides instead of growing. - The answer is the largest window length seen.
Why it is correct
The window length never decreases, and after every step length - max_freq <= budget holds. When max_freq increases, the length grows by at most as much, so the gap does not widen. Otherwise a single left-step restores the gap.
Every recorded length is achievable. max_freq was a true count in some earlier window of length at most the current length. A window of the current length (which never exceeds the string length) can be chosen to contain that earlier window, so it holds at least max_freq copies of that letter and needs at most length - max_freq <= budget rewrites.
The optimum is reached. If the window were still shorter than the optimal length when the right end reaches the end of an optimal block, a contradiction arises: the true count in any prefix of the optimal block already satisfies the budget, so the window would have had no reason to slide past the block's start. Hence the window reaches the optimal length.
A stale max_freq can only stop the window from growing, never let it grow wrongly. The answer improves only when some letter reaches a new highest count, which is exactly when max_freq is refreshed.
Complexity
- Time: O(n), since each character enters and leaves the window at most once, with constant work per step.
- Space: O(1), a fixed array of 26 counters.
Edge cases
budget = 0: the result is the longest existing run.budget >= len(text): the window never becomes invalid, so the answer islen(text).- A string of one repeated letter, or a single character: the answer is the full length.
Reference solution
def longest_block_with_rewrites(text, budget):
counts = [0] * 26
best = 0
max_freq = 0
left = 0
for right, ch in enumerate(text):
idx = ord(ch) - 65
counts[idx] += 1
if counts[idx] > max_freq:
max_freq = counts[idx]
if right - left + 1 - max_freq > budget:
counts[ord(text[left]) - 65] -= 1
left += 1
if right - left + 1 > best:
best = right - left + 1
return best