Easy approach || First count Subarrays with at least k distinct elements
Intuition\nA subarray with atleast k+1 distinct elements is also a subarray with atleast k distinct elements.\nIf we remove the subarrays with atleast k+1 disti
# Intuition\nA subarray with atleast k+1 distinct elements is also a subarray with atleast k distinct elements.\nIf we remove the *subarrays with atleast k+1 distinct elements* from *subarrays with atleast k distinct elements*, there we get the subarrays with exactly k distinct elements.\n\n\n\n# Approach\nCalculate the number Subarrays with atleast k distinct elements and k+1 distinct elements respectively through sliding window with the function:\n\n        *int goodarr(vector<int> &nums,int k)*\n\nSubtract goodarr(nums,k+1) from goodarr(nums,k) to get the count of subarrays with exactly k distinct integers.\n\n\n\n# Complexity\n- Time complexity:\nO(N) For goodarr(nums,k)\nO(N) For goodarr(nums,k+1)\n\n==> O(N+N) ==> **O(N)**\n\n- Space complexity:\n**O(N)**\n\n# Code\n```\nclass Solution {\npublic:\n    //helper function\n    int goodarr(vector<int> &nums,int k)\n    {\n        unordered_map<int,int> mp;   //to store the frequencies of current window\n        int j=0,cnt=0,res=0;\n    //j is the right end of the window and i is the left end\n        for(int i=0;i<nums.size();i++)\n        {\n            j=max(i,j);     //ensure j doesn\'t move back\n        //expand the window until we get k distinct elements in it\n            while(j<nums.size()&&cnt<k)\n            {\n                mp[nums[j]]++;\n                if(mp[nums[j]]==1)\n                cnt++;\n                j++;\n            }\n            if(cnt==k)\n            res+=(nums.size()-j+1);\n\n        //shrink the window by 1 element and reduce count if nums[i] is occuring only once inside the window\n            if(mp[nums[i]]==1)\n            cnt--;\n            mp[nums[i]]--;\n        }\n        return res;\n    }\n    int subarraysWithKDistinct(vector<int>& nums, int k) {\n        return goodarr(nums,k)-goodarr(nums,k+1);\n    }\n};\n```\n\n\nUPVOTE IF YOU FIND IT USEFUL :)\n![image.png](https://assets.leetcode.com/users/images/990bab73-1bf7-4524-a62d-a72a8108a759_1711782223.2041888.png) \n
['Sliding Window', 'C++']