Longest Repeating Char Replace

Python data engineering interview problem. Difficulty: intermediate. Pattern: Sliding Window. About 14 minutes. Part of the Pro drill bank.

Longest same-letter window after at most k replacements. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A text-cleaning job may replace a few characters so a window uses one repeated letter. The goal is to find the longest window that can be made uniform with at most k replacements. Return the length of the longest substring where changing no more than k characters would make every character in that substring the same. The original string is not changed. Write the function character_replacement(s: str, k: int) -> int. For 'ABAB' with k = 2, change the two Bs to A and use all 4 characters, so the answer is 4. The starter file already has the function name and the harness print lines. Keep them, and fill only the function body.

Requirements

  • Use a contiguous window.
  • Allow at most k replacements inside the window.
  • Return only the maximum window length.

Constraints

  • k is a non-negative integer and the string contains characters that can be counted.
  • A window is valid when its length minus its most common count is at most k.

Examples

Input: character_replacement('ABAB', 2) Output: 4 Replace both B or both A.

Topics: lakebench, python, window, replace.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Longest Repeating Char Replace

Interview-style drill: Longest same-letter window after at most k replacements.

Implement `character_replacement(s: str, k: int) -> int`. Example: `"ABAB", 2` → `4`. Keep the harness.