Longest Repeating Character Replacement

Medium#424variable size

You get a string of capital letters and a number k. You may change at most k letters to any other letters. Find the length of the longest piece of one repeated letter you can get. Our example: "ABABBCB" and k = 1 — the answer is 4: change the "A" in "BABB" and get "BBBB".

input
s: a string of capital English letters; k: how many letters you may change, each to any other letter.
returns
The length of the longest piece of letters in a row that can be made one repeated letter with at most k changes.
constraints
  • 1 ≤ s.length ≤ 10⁴
  • s has capital English letters only
  • 0 ≤ k ≤ s.length
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string} s
 * @param {number} k
 * @return {number}
 */
function characterReplacement(s, k) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more sliding window problems

Pattern “Sliding window” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.