Number of substrings with exactly k distinct characters Given a string s and an int k, return an int representing the number of substrings (not unique) of s with exactly k distinct characters. If the given string doesn't have k distinct characters, return 0.
Input: s = &quot;pqpqs&quot;, k = 2
Output: 7
Explanation: [&quot;pq&quot;, &quot;pqp&quot;, &quot;pqpq&quot;, &quot;qp&quot;, &quot;qpq&quot;, &quot;pq&quot;, &quot;qs&quot;]

I have this solution for it:
   def subarraysWithKDistinct(self, A, K):
        return self.atMostK(A, K) - self.atMostK(A, K - 1)

    def atMostK(self, A, K):
        count = collections.Counter()
        res = i = 0
        for j in range(len(A)):
            if count[A[j]] == 0: K -= 1
            count[A[j]] += 1
            while K &lt; 0:
                count[A[i]] -= 1
                if count[A[i]] == 0: K += 1
                i += 1
            res += j - i + 1
        return res

What I don't understand is how does atMost(k) - atMost(k-1) gives the total number of substrings that have exactly k distinct characters? I tried different examples and it works. I understand how the code works but not how the final answer is computed after two-passes.
Can someone give me generic mathematical proof or intuition behind it?
atMost(A, K) computes the number of substrings with at most K distinct characters.
A substring with at most K distinct characters has either exactly K, or at most K-1, distinct characters. So, atMost(A, K) - atMost(A, K-1) is the number of substrings with exactly K distinct characters.