Solving the problem using it's easier version || Easy to understand || Sliding Window && Two Pointer
Intuition\n Describe your first thoughts on how to solve this problem. \nExactly k distinct integers means : Atmost (k) distinct integers - Atmost (k - 1) disti
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nExactly k distinct integers means : **Atmost (k) distinct integers - Atmost (k - 1)** distinct integers.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere I have used sliding window combined with two pointers approach.\n1. **Fix a pointer \'j\'** at the beginning of the array and **traverse the array using \'i\'** and keep on storing the elements in the map, till the size of the map does not exceeds (k).\n2. As it exceeds k, start deleting the elements from the beginning of the array using the j pointer and after deleting the elements increment the j pointer.\n3. Each time calculate the distinct subarrays in the sliding window and add it to our answer.\n4. By performing this algorithm once, **we\'ll get subarrays with atmost k elements.**\n5. **Perform same algorithm for atmost k - 1 elements and subtract the latter from the first part.**\n\n# Complexity\n- Time complexity: **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTraversing the array.\n\n- Space complexity: **O(k)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSize of the map will never exceed k.\n\n# Code\n```\nclass Solution {\npublic:\n    \n    int atmost(vector<int> nums, int k)\n    {\n        int n = nums.size();\n\n        int i = 0, j = 0;\n        int cnt = 0;\n\n        map<int,int> mp;\n\n        while(i < n)\n        {\n            mp[nums[i]]++;\n\n            while(mp.size() > k)\n            {\n                auto it = mp.find(nums[j]);\n                it -> second--;\n\n                if(it -> second == 0) mp.erase(it);\n                j++;\n            }\n            cnt += (i - j + 1);\n            i++;\n        }\n\n        return cnt;\n    }\n\n    int subarraysWithKDistinct(vector<int>& nums, int k) {\n        return atmost(nums, k) - atmost(nums, k - 1);\n    }\n};\n```
['Two Pointers', 'Sliding Window', 'Python', 'C++', 'Java']