Skip to main content
14

Longest Repeating Character Replacement

Mediumsliding windowcounting

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Sliding WindowRead the beginner guide

You're given a string s of uppercase English letters and an integer k. You may replace up to k characters of s with any other uppercase letter.

Return the length of the longest substring that can be made of a single repeated letter.

Understand the problem

  • You may change at most k letters (you can also change fewer, or none).
  • After changing, look for the longest piece of neighbouring letters that are all the same, like "BBBB".
  • You return only the length.

Another way to say it: find the longest piece of s that you could turn into one repeated letter using at most k changes.

Example 1

text
Input:  s = "ABAB", k = 2
Output: 4

Change both As to B → "BBBB", length 4. (Changing both Bs to A works too.)

Example 2

text
Input:  s = "AABABBA", k = 1
Output: 4

Change the A at index 3 to B → "AABBBBA", which contains "BBBB", length 4. No single change gives 5 in a row.

Example 3

text
Input:  s = "AAAA", k = 0
Output: 4

No changes needed: it's already all A.

Constraints

  • 1 <= s.length <= 10^5
  • s contains uppercase English letters only.
  • 0 <= k <= s.length

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Slide a window over the string, and keep it only as wide as can be turned into one letter: its length minus the count of its most common letter must be at most k.

    The naive approach (and why it's slow)

    For every substring, count its letters, find the most common one, and check whether the rest (the letters you'd change) is at most k. There are about n²/2 substrings, so this is at least O(n²). For 100,000 letters, billions of steps.

    The key insight

    First, the rule for one window. To turn a window into a single letter with the fewest changes, keep its most common letter and change the rest:

    text
    window "AABAB": A appears 3 times, B appears 2 times
    keep the A's, change the 2 B's → "AAAAA"
    changes needed = length - maxCount = 5 - 3 = 2

    So a window is valid when length - maxCount <= k.

    Second, slide instead of restarting. Use a sliding window with a letter count (a hash map or a 26-slot array):

    • Add s[right] to the counts, update maxCount.
    • If the window is invalid, drop s[left] from the counts and move left forward.
    • Record the window length.

    Step by step

    s = "AABABBA", k = 1:

    rightLetterWindowCountsmaxCountChanges needed (len - max)Valid?ActionBest
    0AAA:110✅1
    1AAAA:220✅2
    2BAABA:2 B:121✅3
    3AAABAA:3 B:131✅4
    4BAABABA:3 B:232❌drop A, left++ → ABAB4
    5BABABBA:2 B:332❌drop A, left++ → BABB4
    6ABABBAA:2 B:332❌drop B, left++ → ABBA4

    Answer: 4.

    Why maxCount never has to go down

    When we shrink the window, the real most-common count might drop, but the code leaves maxCount alone. That looks like a bug, but it's safe:

    • The answer can only get bigger if some window has a bigger maxCount than we've ever seen (a longer valid window needs more copies of one letter).
    • A stale, too-high maxCount can only keep the window at the size of the best answer so far. It never makes us report a window longer than a real one.

    Also notice the window never shrinks by more than one per step: it either grows or slides. That's why "drop one, move left once" is enough instead of a while loop (the reference code still uses while, which works the same way).

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). Each letter enters the window once and leaves at most once.
    • Memory: O(1). At most 26 letter counts.

    Common mistakes

    • Trying every target letter separately. Running the window 26 times (once per letter) works and is O(26 · n), but it's more code than needed.
    • Recomputing maxCount by scanning the counts after every shrink. Correct, but unnecessary (see above).
    • Forgetting to decrement the count of the letter that leaves on the left.

    Going deeper

    The key move in this problem is turning "can this window be fixed?" into a single number check (length - maxCount <= k). Most sliding window problems hinge on finding that kind of cheap "is the window valid?" test.

    Reference solution

    js
    /**
     * @param {string} s
     * @param {number} k
     * @return {number}
     */
    export default function characterReplacement(s, k) {
      // letter -> how many times it appears in the window s[left..right]
      const counts = new Map()
      let left = 0
      let maxCount = 0 // the highest count of a single letter we've seen in a window
      let best = 0
      for (let right = 0; right < s.length; right++) {
        // Add the new letter to the window.
        const count = (counts.get(s[right]) ?? 0) + 1
        counts.set(s[right], count)
        maxCount = Math.max(maxCount, count)
        // Letters to change = window length - most common letter. Too many? Shrink.
        // (maxCount is never lowered: a stale value can't make us report a too-long window.)
        while (right - left + 1 - maxCount > k) {
          counts.set(s[left], counts.get(s[left]) - 1)
          left++
        }
        best = Math.max(best, right - left + 1)
      }
      return best
    }
    ts
    export default function characterReplacement(s: string, k: number): number {
      // letter -> how many times it appears in the window s[left..right]
      const counts = new Map<string, number>()
      let left = 0
      let maxCount = 0 // the highest count of a single letter we've seen in a window
      let best = 0
      for (let right = 0; right < s.length; right++) {
        // Add the new letter to the window.
        const count = (counts.get(s[right]) ?? 0) + 1
        counts.set(s[right], count)
        maxCount = Math.max(maxCount, count)
        // Letters to change = window length - most common letter. Too many? Shrink.
        // (maxCount is never lowered: a stale value can't make us report a too-long window.)
        while (right - left + 1 - maxCount > k) {
          counts.set(s[left], (counts.get(s[left]) ?? 0) - 1)
          left++
        }
        best = Math.max(best, right - left + 1)
      }
      return best
    }
    python
    from collections import defaultdict
    
    
    def character_replacement(s: str, k: int) -> int:
        # letter -> how many times it appears in the window s[left..right]
        counts = defaultdict(int)
        left = 0
        max_count = 0  # the highest count of a single letter we've seen in a window
        best = 0
        for right, char in enumerate(s):
            # Add the new letter to the window.
            counts[char] += 1
            max_count = max(max_count, counts[char])
            # Letters to change = window length - most common letter. Too many? Shrink.
            # (max_count is never lowered: a stale value can't make us report a too-long window.)
            while right - left + 1 - max_count > k:
                counts[s[left]] -= 1
                left += 1
            best = max(best, right - left + 1)
        return best