Sign inEnroll free
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.

The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(n) · space O(1)
def characterReplacement(s: str, k: int) -> int:
    count = {}
    l = best = maxCount = 0
    for r, c in enumerate(s):
        count[c] = count.get(c, 0) + 1
        maxCount = max(maxCount, count[c])
        if (r - l + 1) - maxCount > k:
            count[s[l]] -= 1
            l += 1
        best = max(best, r - l + 1)
    return best
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough