DSA Visualizer · 25 visualizationsLongest Repeating Character Replacement
MediumSliding Window

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.

s = "AABABBA", k = 1Step 1 of 9
A
0l
A
1
B
2
A
3
B
4
B
5
A
6

Start with an empty window and empty character counts.

Pythontime O(n) · space O(26)
1def characterReplacement(s, k):
2 count = {}
3 left = 0
4 maxCount = 0
5 best = 0
6 for right in range(len(s)):
7 ch = s[right]
8 count[ch] = count.get(ch, 0) + 1
9 maxCount = max(maxCount, count[ch])
10 if (right - left + 1) - maxCount > k:
11 count[s[left]] -= 1
12 left += 1
13 best = max(best, right - left + 1)
14 return best
Variables
left0
right—
maxCount0
best0

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

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

Replace the 2 A's or the 2 B's to get AAAA or BBBB

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

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

Brute force

Try every substring, count its most frequent character, and check whether the rest fits within k replacements.

Time O(n²) or O(n³) depending on how the count is recomputedSpace O(26)
Optimal

Sliding window with a running character count and a running max count; shrink from the left only when the window becomes invalid.

Time O(n)Space O(26)

Complexity

Time O(n)Space O(26)

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).
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free