Python | Hashmap | Sliding Window | Simple Solution Wiith Explanation
Logic:\n1. To directly count the subarrays with exactly K different integers is hard but to find the count of subarrays with at most K different integers is eas
## Logic:\n1. To directly count the subarrays with exactly K different integers is hard but to find the count of subarrays with at most K different integers is easy. \n2. So the idea is to find the count of subarrays with at most K different integers(fn(K)), and the count of subarrays with at most (K \u2013 1) different integers(fn(K \u2013 1)) and finally take their difference, fn(K) \u2013 fn(K \u2013 1) which is the required answer.\n3. Now, count of subarrays with at most K different elements can be easily calculated through the sliding window technique. \n4. The idea is to keep expanding the right boundary of the window till the count of distinct elements in the window is less than or equal to K and when the count of distinct elements inside the window becomes more than K, start shrinking the window from the left till the count becomes less than or equal to K. Also for every expansion, keep counting the subarrays as end \u2013 start + 1.\n\n```\nclass Solution:\n    def atMostKDistinct(self, nums, k):\n        hashmap = {}\n        subarrays = 0\n        start, end = 0, 0\n        while end < len(nums):\n            if nums[end] in hashmap:\n                hashmap[nums[end]] += 1\n            else:\n                hashmap[nums[end]] = 1\n            while len(hashmap) > k:\n                hashmap[nums[start]] -= 1\n                if hashmap[nums[start]] == 0:\n                    del hashmap[nums[start]]\n                start += 1\n            subarrays += end-start+1\n            end += 1\n        return subarrays\n    \n    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n        return self.atMostKDistinct(nums, k) - self.atMostKDistinct(nums, k-1)\n```\n\n***If you liked the above solution then please upvote!***
['Sliding Window', 'Python']