KatInterview

Longest Repeated-Letter Block With a Limited Rewrite Budget

StringsAuto-graded · 26 test cases
MediumAuto-gradedStringssliding-windowstringstwo-pointers

Last 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 budget rewrites, or none at all, is allowed.
  • The answer is the maximum block length over every allowed way of using at most budget rewrites.

Constraints

  • 1 <= len(text) <= 10^5
  • text contains 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.