Longest Repeating Character Replacement

Find the length of the longest substring containing all repeating letters you can get after changing at most k characters. Tags: String

Try It!

Discussion

Video

Solution

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        left = 0
        right = 0
        max_len = 0
        max_count = 0 
        char_counter = {}
        
        while right < len(s):
            c = s[right]
            if c not in char_counter:
                char_counter[c] = 0    
            char_counter[c] += 1
            max_count = max(max_count, char_counter[c])
            
            while right - left + 1 - max_count > k:
                c = s[left]
                char_counter[c] -= 1
                left += 1
            
            max_len = max(max_len, right - left + 1)
            right += 1
        
        return max_len