Skip to content

Instantly share code, notes, and snippets.

@KirillLykov
Last active June 20, 2019 20:53
Show Gist options
  • Save KirillLykov/27bc75db5f7cb1542c5c050e7b707d1b to your computer and use it in GitHub Desktop.
Save KirillLykov/27bc75db5f7cb1542c5c050e7b707d1b to your computer and use it in GitHub Desktop.
Count all subarrays with at exactly k different elements

Interesting problem on sliding window: lc

The idea of solution is to solve a simpler problem - count subarrays with at most K distinct characters. This one is similar to longest substr without repeating characters

class Solution {
public:
    int subarraysWithKDistinct(vector<int>& A, int K) {
        return atMostK(A, K) - atMostK(A, K - 1);
    }
    
    int atMostK(vector<int>& A, int K) {
        int res = 0;
        unordered_map<int,int> freq;
        int l = 0;
        for (int r = 0; r < A.size(); ++r) {
            if (freq[A[r]] == 0)
                --K;
            ++freq[A[r]];
            // get rid of elements from left
            while (K < 0) {
                --freq[A[l]];
                if (freq[A[l]] == 0)
                    ++K;
                ++l;
            }
            // number of subarrays ending at r-th element
            res += r - l + 1;
        }
        
        return res;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment