✅✅Faster || Easy To Understand || C++ Code
Using Sliding Window And Unordered Map\n\n Time Complexity : O(N)\n\n Space Complexity : O(N)\n\n\nclass Solution {\npublic:\n    \n    int count_at_most(vector
* ***Using Sliding Window And Unordered Map***\n\n* ***Time Complexity : O(N)***\n\n* ***Space Complexity : O(N)***\n\n```\nclass Solution {\npublic:\n    \n    int count_at_most(vector<int>& nums, int k)\n    {\n        int n = nums.size();\n        \n        unordered_map<int, int> mp;\n        \n        int left = 0;\n        \n        int count = 0;\n        \n        for(int right = 0; right < n; right++)\n        {\n            mp[nums[right]]++;\n            \n            while(mp.size() > k)\n            {\n                mp[nums[left]]--;\n                \n                if(mp[nums[left]] == 0)\n                {\n                    mp.erase(nums[left]);\n                }\n                \n                left++;\n            }\n            \n            int curr_count = right - left + 1;\n            \n            count += curr_count;\n        }\n        \n        return count;\n    }\n    \n    int subarraysWithKDistinct(vector<int>& nums, int k) {\n        \n        int count_at_most_k = count_at_most(nums, k);\n        \n        int count_at_most_k_1 = count_at_most(nums, k - 1);\n        \n        int count_exactly_k = count_at_most_k - count_at_most_k_1;\n        \n        return count_exactly_k;\n    }\n};\n```
['C', 'Sliding Window']