Easy Sliding Window Approach!!!
Approach\n Describe your approach to solving the problem. \n\n1. Initialize an unordered map mp to store element frequencies.\n2. Initialize ans, l, temp, and s
# Approach\n<!-- Describe your approach to solving the problem. -->\n```\n1. Initialize an unordered map mp to store element frequencies.\n2. Initialize ans, l, temp, and s to 0.\n3. Iterate i and j from 0 to n-1:\n   a. If nums[j] not in mp, increment l.\n   b. Increment frequency of nums[j] in mp.\n   c. If l > k, shrink the window:\n      - Decrement frequency of nums[i] in mp.\n      - If frequency becomes 0, remove nums[i] from mp and decrement l.\n      - Update temp to mark starting index of next valid subarray.\n   d. If l == k:\n      - Iterate from i to temp:\n         * Reduce frequency of nums[i] until it becomes 1.\n      - If s is true, ans += (i - temp + 1), else ans += (i + 1).\n4. Return ans.\n```\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int subarraysWithKDistinct(vector<int>& nums, int k) {\n        int n = nums.size();\n        unordered_map<int, int> mp;\n\n        int ans = 0, temp=0, l=0;\n        bool s=false;\n\n        for(int i=0, j=0; j<n; j++) {\n            if(mp[nums[j]]==0) l++;\n            mp[nums[j]]++;\n\n            while(l>k) {\n                mp[nums[i]]--;\n                if(mp[nums[i]]<=0) mp[nums[i]]=0, l--;\n                i++;\n                temp=i;\n                s=true;\n            }\n\n            if(l==k) {\n                while(mp[nums[i]]>1) {\n                    mp[nums[i]]--;\n                    i++;\n                }\n                if(s) ans+=i-temp+1;\n                else ans+=i+1;\n            }\n        }\n        return ans;\n    }\n};\n```
['Array', 'Hash Table', 'Sliding Window', 'Counting', 'C++']