Longest Repeating Character Replacement

MediumSliding window

You are given a string s of uppercase letters and an integer k. You may change at most k characters of s, each to any uppercase letter.

Return the length of the longest substring, a run of consecutive characters, that can be made of one repeated letter after your changes.

Examples

Example 1
Input:  s = "BAAAB", k = 1
Output: 4

Change the first B to A, and AAAA is four long.

Example 2
Input:  s = "XYZ", k = 0
Output: 1

With no changes allowed, the longest run of one letter is one letter.

Constraints

  • 1 ≤ s.length ≤ 10⁵
  • 0 ≤ k ≤ s.length
  • s uses uppercase English letters only.

Stuck?

Hint 1

A window can become one letter when its length minus the count of its most common letter is at most k.

Hint 2

Slide a window with letter counts. Grow it on the right, and when it needs more than k changes, move the left edge in by one.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur