[C++] O(N) sliding window [Detailed Explanation]
\n/*\n    https://leetcode.com/problems/subarrays-with-k-different-integers/submissions/\n    \n    We use a different problem to solve this. We find the number
```\n/*\n    https://leetcode.com/problems/subarrays-with-k-different-integers/submissions/\n    \n    We use a different problem to solve this. We find the number of substrings with atmost\n    K unique chars. \n    substrings with exactly k = atmost unique (K) - atmost unique (K-1)\n    This diff only leaves the substrings with exactly k unique chars\n*/\nclass Solution {\npublic:\n    // Finds the substring with atmost K unique chars\n    int atmostK(vector<int>& arr, int K) {\n        int i = 0, j = 0, substrings = 0;\n        unordered_map<int, int> freq;\n        const int N = arr.size();\n        \n        while(i < N) {\n            // Expand the window\n            if(K >= 0) {\n                ++freq[arr[i]];\n                if(freq[arr[i]] == 1)\n                    --K;\n                ++i;\n            }\n            // make the window valid\n            while(K < 0) {\n                --freq[arr[j]];\n                if(freq[arr[j]] == 0)\n                    ++K;\n                ++j;\n            }\n            // Each valid window adds the subarrays which satisfies the condition\n            // For : 1,2,1, k=2\n            // 1: [1] \n            // 2: [2], [1,2]\n            // 3: [1,2], [2,1], [1,2,1]\n            substrings += i - j + 1;\n        }\n        return substrings;\n    }\n    \n    int subarraysWithKDistinct(vector<int>& arr, int K) {\n        return atmostK(arr, K) - atmostK(arr, K-1);\n    }\n};\n```
['C', 'C++']