Skip to content
Problem 424 · LeetCode 424(opens in a new tab)

Longest Repeating Character Replacement

MediumHash tables

You get a string s of capital letters and a number k. You may pick up to k positions in the string and change the letter at each one to any other capital letter.

After your changes, look for the longest stretch of neighbouring positions where every letter is the same. Return the length of the longest such stretch you can make.

Example 1

Input:  s = "ABBCB", k = 1
Output: 4
Why:    change the C in "BBCB" to get "BBBB"
2 more examples and the constraints

Example 2

Input:  s = "XYYX", k = 0
Output: 2
Why:    no changes allowed; "YY" is the longest run

Example 3

Input:  s = "QQQ", k = 2
Output: 3
Why:    the whole string already matches

Constraints

  • 1 ≤ length of s ≤ 100,000
  • s holds only the capital letters A to Z
  • 0 ≤ k ≤ length of s

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every substringO(n²)
  2. Sliding windowO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 lettersVerdict
Every substringO(n²)
Mention it, then move on
Sliding windowO(n)
Best; one pass

n = length of s.

Edge cases to test

  • k = 0. No changes: the answer is the longest run that is already uniform, e.g. "XYYX" gives 2.
  • k at least the length. Every letter can change, so the answer is the whole length, e.g. "ABCD" with k = 4.
  • One letter. "Z" gives 1 for any k.
  • Best stretch at the end. The window must still be measured after the last letter is read.

Common mistakes

  • Thinking you need to know which letter to keep; the most common one in the window is always the cheapest.
  • Recomputing most by scanning all counts after every shrink, or lowering it, and losing the O(n) bound or the right answer.
  • Returning more than the length of s when k is large; the window cannot grow past the string.

How to talk through it

  1. 1Clarify. Only capital letters? Can k be 0, or bigger than the string? Must the stretch be contiguous?
  2. 2Give the brute force. Try every substring; it needs length − most changes. Say it is O(n²).
  3. 3State the window rule. A window is fine when length − most ≤ k. Grow right, slide left when it breaks.
  4. 4Explain why most never drops. Only a bigger most can produce a longer valid window, so a stale most is harmless.
  5. 5Test out loud. Run "XYYX" with k = 0 and "ABCD" with k = 4 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?