☰ All problems

Longest Repeating Character Replacement

A row of floor tiles is described by the string s, where each uppercase letter names the colour of one tile. A decorator may repaint at most k tiles, giving each repainted tile any colour they like.

Return the length of the longest stretch of adjacent tiles that can be made all one colour using those repaints.

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

Explanation: Repaint the G to get RRRR across the first four tiles. Covering all five would need two repaints.

Example 2
Input: s = "PQQPQQQ", k = 2
Output: 7

Explanation: Repainting both P tiles turns the whole row into Q.

Example 3
Input: s = "ZYXW", k = 0
Output: 1

Explanation: With no repaints allowed, the longest single-colour stretch is one tile.

Constraints

  • The row has between 1 and 10^5 tiles.
  • Every character of s is an uppercase English letter.
  • k is between 0 and the length of s.
💡 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