Longest Substring with At Most K Distinct Characters

Problem Link 1: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/

Problem Link 2: https://www.lintcode.com/problem/386/

class Solution:
    """
    @param s: A string
    @param k: An integer
    @return: An integer
    """
    def length_of_longest_substring_k_distinct(self, s: str, k: int) -> int:
        # write your code here
        n=len(s)
        d={}
        j=0
        ans=0
        for i in range(n):
            if(s[i] not in d):
                d[s[i]]=1
            else:
                d[s[i]]+=1
            
            while(len(d)>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