2
https://leetcode.com/problems/subarrays-with-k-different-integers/submissions/4
We use a different problem to solve this. We find the number of substrings5
with atmost K unique chars. substrings with exactly k = atmost unique (K) -6
atmost unique (K-1) This diff only leaves the substrings with exactly k11
// Finds the substring with atmost K unique chars12
int atmostK(vector<int> &arr, int K) {13
int i = 0, j = 0, substrings = 0;14
unordered_map<int, int> freq;15
const int N = arr.size();21
if (freq[arr[i]] == 1) --K;24
// make the window valid27
if (freq[arr[j]] == 0) ++K;30
// Each valid window adds the subarrays which satisfies the condition34
// 3: [1,2], [2,1], [1,2,1]35
substrings += i - j + 1;40
int subarraysWithKDistinct(vector<int> &arr, int K) {41
return atmostK(arr, K) - atmostK(arr, K - 1);