KatInterview

Longest Uniform Stretch With a Swap Budget

StringsAuto-graded · 27 test cases
MediumAuto-gradedStringssliding-windowstringsfrequency-counting

Last 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 budget operations is perfectly fine. When budget = 0, no changes are allowed, so the answer is the length of the longest run of one letter already in text.
  • Return only the length of the block, not the block itself or the target letter.

Constraints

  • 1 <= len(text) <= 100 000
  • text contains only uppercase English letters 'A' through 'Z'
  • 0 <= budget <= len(text)
  • The answer is an integer between 1 and len(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.