340 Longest Substring With At Most K Distinct Characters
Approach 1 Sliding Window
fromcollectionsimportdefaultdictclassSolution:deflengthOfLongestSubstringKDistinct(self,s:str,k:int)->int:""" k distinct chars + x overlapping chars 2 pointers, same direction, right: moves only distinct < k (use a counter for freq) left: moves when we have len(counter) > k maintain a variable for global maximum """ifk==0:return0left=0counter=defaultdict(int)global_max=0forrightinrange(len(s)):counter[s[right]]+=1whilelen(counter)>kandleft<right:counter[s[left]]-=1# clean it if it's zeroifcounter[s[left]]==0:delcounter[s[left]]left+=1# if reach here, it must be <= kglobal_max=max(global_max,right-left+1)returnglobal_max