C++ | Sliding Window with 3 Pointers
I used two pointers l and r to maintain the largest window which has exact k different numbers ended at r.\n2. A third pointer p is inbetween l and r. p is sque
1. I used two pointers `l` and `r` to maintain the **largest** window which has exact `k` different numbers ended at `r`.\n2. A third pointer `p` is inbetween `l` and `r`. `p` is squeezed from `l` towards `r` and stops at the **smallest** window with  `k` distinct elements ened at `r`.\n3. The counting process is at each step at `r`, counts the number of the subarrays ends at `r` and this is `p-l+1`\n\nTime Complexity: O(n)\nSpace Complexity: O(n)\n\nSee the following example, nums = [1,2,1,2,3,3,4,5] and k = 5\nthe last column is the number of the subarrays which has exact `k` different numbers. The final result is the sum over the results in the last column for each row.\n![image](https://assets.leetcode.com/users/images/97625ce2-31fa-4c55-93e4-7a336bbd2c51_1636490645.8440108.png)\n\n```\nclass Solution {\npublic:\n    int subarraysWithKDistinct(vector<int>& nums, int k) {\n        unordered_map<int,int> freq;\n        unordered_map<int,int> freq_in;\n        int l =0, r=0, p = 0;\n        int n = nums.size();\n        int sum = 0;\n        int counts = 0;\n        while(r<n){\n            freq[nums[r]]++;\n            freq_in[nums[r]]++;\n            if(freq[nums[r]]==1){\n                counts++;\n            }\n            while(counts>k){\n                freq[nums[l]]--;\n                freq_in[nums[l]]=freq[nums[l]];\n                if(freq[nums[l]]==0){\n                    counts--;\n                }\n                l++;\n                p=l;\n            } \n            if(counts==k){\n                while(freq_in[nums[p]]!=1){\n                    freq_in[nums[p]]--;\n                    p++;\n                }      \n                sum += (p-l+1);\n            }\n            r++;\n        }\n        return sum;\n    }\n};\n\n```
[]