Subarrays with K Different Integers (Leetcode 992)

Problem Link: https://leetcode.com/problems/subarrays-with-k-different-integers/

class Solution:
    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
           
        def atmostK(nums,k):
            
            j=0
            n=len(nums)
            ans=0
            d={}
            for i in range(n):
                if(nums[i] not in d):
                    d[nums[i]]=1
                else:
                    d[nums[i]]+=1
                
                while(len(d)>k):
                    
                    if(d[nums[j]]==1):
                        del d[nums[j]]
                        j+=1
                    else:
                        d[nums[j]]-=1
                        j+=1
                
                ans=ans+(i-j+1)
            
            return ans
        
        return atmostK(nums,k)-atmostK(nums,k-1)

Last updated