Longest Uniform Stretch With a Swap Budget
StringsAuto-graded · 27 test casesLast updated
Tests efficient sliding-window reasoning to find the longest substring that can be made all one character using at most k single-character replacements.
Problem
You have a string text of uppercase English letters and an integer budget. You can change any letter in text to any other uppercase English letter, and you may do this up to budget times total.
Find the length of the longest contiguous block of characters that you can turn into a single repeated letter by spending at most budget operations.
Rules
- Only the characters inside the block you choose need to become uniform. Characters outside it are irrelevant, and no operations need to be spent on them.
- Spending fewer than
budgetoperations is perfectly fine. Whenbudget = 0, no changes are allowed, so the answer is the length of the longest run of one letter already intext. - Return only the length of the block, not the block itself or the target letter.
Constraints
1 <= len(text) <= 100 000textcontains only uppercase English letters'A'through'Z'0 <= budget <= len(text)- The answer is an integer between
1andlen(text)inclusive and is uniquely determined by the input.
Examples
Example 1
Input: longest_uniform_stretch('ABBCB', 1)
Output: 4
Example 2
Input: longest_uniform_stretch('AAAB', 0)
Output: 3
Example 3
Input: longest_uniform_stretch('XYZXYX', 2)
Output: 4
Hints
Hint 1
For a fixed window, the fewest operations needed to make it uniform equals the window length minus the count of its most frequent letter. A window is affordable when that number is at most budget.
Hint 2
Maintain a sliding window with two pointers. As you extend the right end, track the highest single-letter count seen so far inside the window. This lets you check feasibility in O(1) per step.
Hint 3
The window never needs to shrink — it only slides. When the current window becomes too expensive, advance the left pointer by exactly one rather than collapsing the window. The final window length is the answer.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight
To make a window of length L uniform as cheaply as possible, keep its most frequent letter and replace everything else. If the dominant letter appears f times, you need exactly L - f replacements. The window is affordable when:
window_length - max_frequency_in_window <= budget
So the problem reduces to finding the longest window satisfying that inequality.
Sliding window that only slides, never shrinks
Maintain a window [left, right] and a 26-entry frequency array for the letters inside it. As right advances one step at a time:
- Add the new letter to the counts and update
mx, the running high-water mark of any single-letter count seen in any window so far. - Check feasibility: if
right - left + 1 - mx > budget, advanceleftby one and decrement its letter's count.
The key design choice is that left moves at most once per step, so the window length never decreases — it either grows by one or stays the same. The final length len(text) - left is therefore the maximum length ever achieved.
Why a stale mx is safe
After letters leave the left of the window, mx may overstate the true maximum count inside the current window. This is intentional and safe for two reasons:
- No false negatives. If a feasible window of the candidate length exists ending at
right, its true dominant countfsatisfieslength - f <= budget. Sincemx >= f(the window's true max), the check passes and the window grows. - No false positives. When
mxwas last updated, it reflected a real windowWwith that many copies of one letter. Because window lengths never decrease, we can always stretchWto the current candidate length without reducing that letter's count, meaning a genuinely feasible window of that length exists somewhere in the string.
Together these guarantee that after each step the window length equals the best answer for the prefix ending at right.
Edge cases
budget = 0: only runs of identical letters are feasible, so the answer is the longest existing run.budget >= len(text): the whole string is always affordable; the answer islen(text).- Single character: the window starts at length 1, which always needs 0 replacements, so the answer is at least 1.
- All identical letters:
mxtracks the full window and the answer islen(text).
Complexity
- Time: O(n) — each pointer moves at most
ntimes; each step does O(1) work. - Space: O(n) for the
codeslist (pre-computed letter indices). The 26-entrycntarray is O(1). Computingord(c) - 65inline in the loop would reduce space to O(1) at the cost of slightly more overhead per iteration in Python.
Walkthrough — text = "XYZXYX", budget = 2
| right | char | X count | Y count | Z count | mx | len − mx | action | left |
|---|---|---|---|---|---|---|---|---|
| 0 | X | 1 | 0 | 0 | 1 | 0 | grow | 0 |
| 1 | Y | 1 | 1 | 0 | 1 | 1 | grow | 0 |
| 2 | Z | 1 | 1 | 1 | 1 | 2 | grow | 0 |
| 3 | X | 2 | 1 | 1 | 2 | 2 | grow | 0 |
| 4 | Y | 2 | 2 | 1 | 2 | 3 | slide (drop X) | 1 |
| 5 | X | 2 | 2 | 1 | 2 | 3 | slide (drop Y) | 2 |
Final length: 6 - 2 = 4. ✓
Reference solution
def longest_uniform_stretch(text: str, budget: int) -> int:
cnt = [0] * 26 # per-letter counts inside the window
codes = [ord(c) - 65 for c in text] # convert 'A'..'Z' to 0..25
left = 0
mx = 0 # highest single-letter count seen so far
for right in range(len(codes)):
c = codes[right]
cnt[c] += 1
if cnt[c] > mx:
mx = cnt[c]
# If replacements needed exceed budget, slide the window (don't shrink it).
if right - left + 1 - mx > budget:
cnt[codes[left]] -= 1
left += 1
# The window never shrinks, so its final length is the maximum ever achieved.
return len(codes) - left
Common pitfalls
- Shrinking with a
whileloop and forgetting a running max. Usingwhileto collapse the window and then returningright - left + 1directly gives wrong answers; you need a separatebestvariable to track the maximum length seen. - Recomputing
max(cnt)every step. Correct but costs O(26) per step (still O(n) overall). The high-water-mark trick avoids it entirely. - Using
>=in the feasibility check. That rejects windows needing exactlybudgetreplacements, which are valid. - Trying each of the 26 target letters with a separate pass. Correct and O(26n), but the single-pass version above is worth understanding.