longest-repeating-character-replacement.sh — zsh
stringssliding-windowhashmap

You are given an uppercase English string s and an integer k. You can choose any character in the string and replace it with any other uppercase English letter, at most k times.

Return the length of the longest substring containing the same letter you can obtain after performing at most k replacements.

Input / output

  • Input: s: string, k: int
  • Output: int — maximum length of a valid repeating-character substring

Constraints

  • 1 <= s.length <= 10^5
  • s consists of only uppercase English letters (A–Z)
  • 0 <= k <= s.length

Follow-up

Why don't we need to recompute the exact maximum frequency in the window when shrinking from the left?

Examples
Example 1
Input: s = "ABAB", k = 2
Output: 4
Example 2
Input: s = "AABABBA", k = 1
Output: 4
Example 3: already uniform
Input: s = "AAAA", k = 0
Output: 4