☰ All problems

19. Longest Repeating Character Replacement

You are given a string s of uppercase English letters and an integer k. You may pick at most k positions in s and change the letter at each of them to any other uppercase letter.

Return the length of the longest substring that can be made to consist of a single repeated letter using those changes.

Example 1
Input: s = "BAAB", k = 1
Output: 3

Explanation: Change the first B to get "AAAB"; its first three letters are all A. Making all four equal would need two changes.

Example 2
Input: s = "XYYXYYY", k = 1
Output: 6

Explanation: Change the X at index 3: "YYYYYY" from index 1 to 6.

Example 3
Input: s = "ABCDE", k = 2
Output: 3

Explanation: Any three neighbouring letters can be made equal with two changes.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of uppercase English letters
  • 0 <= k <= s.length
💡 Hint 1

A window can be turned into one repeated letter when windowLength - (count of its most frequent letter) <= k.

💡 Hint 2

Slide a window over s with 26 letter counters. Grow it on the right; when it needs more than k changes, shrink it from the left.

💡 Hint 3

You only care about windows longer than the best one so far, so the "most frequent count" never needs to be decreased when the window shrinks.

/**
 * @param {string} s
 * @param {number} k
 * @return {number}
 */
function characterReplacement(s, k) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc