Python | Sliding Window
see the Successfully Accepted Submission\n\n# Code\n\nfrom collections import defaultdict\n\nclass Solution:\n    def subarraysWithKDistinct(self, nums: List[in
[see the Successfully Accepted Submission](https://leetcode.com/problems/subarrays-with-k-different-integers/submissions/1217969110/?source=submission-ac)\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n        def atMostK(nums, k):\n            counter = defaultdict(int)\n            distinct = 0\n            left = 0\n            result = 0\n\n            for right in range(len(nums)):\n                if counter[nums[right]] == 0:\n                    distinct += 1\n                counter[nums[right]] += 1\n\n                while distinct > k:\n                    counter[nums[left]] -= 1\n                    if counter[nums[left]] == 0:\n                        distinct -= 1\n                    left += 1\n\n                result += right - left + 1\n\n            return result\n\n        return atMostK(nums, k) - atMostK(nums, k - 1)\n\n```\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)
['Python3']