C++ || Sliding Window || O(N)
Connect with me on LinkedIn: https://www.linkedin.com/in/abhay5349singh/\n\nApproach:\n countimg subarrays with AtMost k distinct - AtMost (k-1) distinct elemen
**Connect with me on LinkedIn**: https://www.linkedin.com/in/abhay5349singh/\n\n**Approach:**\n* countimg subarrays with AtMost k distinct - AtMost (k-1) distinct elements\n* if a subarray has AtMost k distinct then it means all subarrays that either have [1 distinct, 2 distinct, .... or k distinct] elements will be part of it, now if we reduce count of subarray that either have [1 distinct, 2 distinct, .... or (k-1) distinct] elements, it should give us a count of subarrays which have exactly k distinct elements.\n* number of new subarrays formed with addition of 1 element in end = j-i+1\n\n```\nclass Solution {\npublic:\n    \n    int countSubarraysWithAtMostKDistinct(vector<int>& nums, int k){\n        int n=nums.size();\n        \n        unordered_map<int, int> mp;\n        \n        int i=0, j=0;\n        \n        int c=0;\n        \n        while(j<n){\n            mp[nums[j]]++;\n            \n            while(i<=j && mp.size()>k){\n                if(--mp[nums[i]] == 0) mp.erase(nums[i]);\n                i++;\n            }\n            \n            c += (j-i+1);\n            \n            j++;\n        }\n        \n        return c;\n    }\n    \n    int subarraysWithKDistinct(vector<int>& nums, int k) {\n        return countSubarraysWithAtMostKDistinct(nums,k)-countSubarraysWithAtMostKDistinct(nums,k-1);\n    }\n};\n```\n\n**Do upvote if it helps :)**
['C++']