classSolution:defsubarraysWithKDistinct(self,nums: List[int],k:int) ->int:defatMostK(k): fast =0 slow =0 memo =defaultdict(int) res =0while fast <len(nums): char = nums[fast] fast +=1 memo[char]+=1whilelen(memo)> k: d = nums[slow] slow +=1 memo[d]-=1if memo[d]==0:del memo[d] res += fast - slowreturn resreturnatMostK(k)-atMostK(k -1)