***Longest Repeating Character Replacement (Leetcode 424)

Problem Link: https://leetcode.com/problems/longest-repeating-character-replacement/

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        
        ans=0
        j=0
        n=len(s)
        c=0
        d={}
        maxCount=0
        for i in range(n):
            if(s[i] not in d):
                d[s[i]]=1
            else:
                d[s[i]]+=1
            
            maxCount=max(maxCount,d[s[i]])
            
            ## We can account for subsequence by 
            ## removing the char at the start of the 
            ## subsequence by doing count[i-max_length] -= 1.
            ## i-maxlength returns the char at the start
            ## of the subsequence. 
            
            ## We don't update the max_count again here because 
            ## we want max_count to only refer to the max_count 
            ## of the answer's subsequence. Doing this trick is 
            ## what allows the subsequence property to be maintained.
            ## By only considering the count of the max_char, 
            ## we don't have to keep track of which char we are actually 
            ## talking about, only the max one. This allows us to ignore 
            ## the distinction between AAAA and BBBB because we only care 
            ## about the max_length.
            
            while((i-j+1)-maxCount>k):
                if(d[s[j]]==1):
                    del d[s[j]]
                    j+=1
                else:
                    d[s[j]]-=1
                    j+=1
                         
            ans=max(ans,i-j+1)
        
        return ans      

Last updated