DSA Visualizer · 25 visualizationsLongest Repeating Character Replacement
Longest Repeating Character Replacement
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character, at most k times. Return the length of the longest substring containing the same letter after performing the operations.
Start with an empty window and empty character counts.
Problem
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character, at most k times. Return the length of the longest substring containing the same letter after performing the operations.
Examples
Replace the 2 A's or the 2 B's to get AAAA or BBBB
Constraints
- 1 ≤ s.length ≤ 10⁵
- s consists of only uppercase English letters
- 0 ≤ k ≤ s.length
Intuition
A window is achievable with at most k replacements exactly when (window length) − (count of its most frequent character) ≤ k — that's how many characters would need to change. Slide a window right one character at a time, tracking counts and the best count seen so far; whenever the window needs more than k replacements, shrink it from the left by one. The window never needs to shrink by more than one at a time, so the whole scan stays linear.
Brute force → Optimal
Try every substring, count its most frequent character, and check whether the rest fits within k replacements.
Sliding window with a running character count and a running max count; shrink from the left only when the window becomes invalid.
Complexity
Edge cases
- k = 0: the answer is just the length of the longest run of one repeated character already in s.
- k ≥ s.length: the whole string can be replaced, so the answer is s.length.
Common mistakes
- Shrinking the window by more than one step at a time — only ever needs one step, since the window grew by exactly one character.
- Decreasing maxCount when the window shrinks — it doesn't need to, and leaving it stale is actually what keeps the algorithm linear (the window only ever grows to its best-so-far size or larger).