Python Sliding Window
\nclass Solution:\n    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n        def atMostK(nums, k):\n            n = len(nums)\n            
```\nclass Solution:\n    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n        def atMostK(nums, k):\n            n = len(nums)\n            left, right = 0, 0\n\n            res = 0\n\n            from collections import Counter\n            counter = Counter()\n\n            while right < n:\n                counter[nums[right]] += 1\n\n                while len(counter) > k:\n                    counter[nums[left]] -= 1\n                    if counter[nums[left]] == 0:\n                        del counter[nums[left]]\n\n                    left += 1\n\n                res += right - left + 1\n                right += 1\n\n            return res\n        \n        return atMostK(nums, k) - atMostK(nums, k-1)\n```\n\n![image](https://assets.leetcode.com/users/images/ebe39cb4-4f95-4e57-8e4c-1bae25544113_1642332679.8178716.png)\n
['Sliding Window', 'Python']