[Python3] sliding window + queue
\n\nclass Solution:\n    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n        ans = ii = 0 \n        freq = defaultdict(int)\n        queu
\n```\nclass Solution:\n    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n        ans = ii = 0 \n        freq = defaultdict(int)\n        queue = deque()\n        for i, x in enumerate(nums): \n            freq[x] += 1\n            queue.append(i)\n            if len(freq) > k: \n                ii = queue[0]+1\n                freq.pop(nums[queue.popleft()])\n            while freq[nums[queue[0]]] > 1: freq[nums[queue.popleft()]] -= 1\n            if len(freq) == k: ans += queue[0] - ii + 1\n        return ans \n```
['Python3']