short python (two pointers O(k) space)
Explantion is same as Yaang\'s in the comment section below\n```\nclass Solution(object):\n    def subarraysWithKDistinct(self, A, K):\n        s = collections.
Explantion is same as Yaang\'s in the comment section below\n```\nclass Solution(object):\n    def subarraysWithKDistinct(self, A, K):\n        s = collections.Counter() \n        l = r = ans = 0 \n        for i,num in enumerate(A):\n            s[num] += 1\n            if s[num] == 1 and len(s) == K:\n                while r < len(A) and A[r] in s:\n                    r += 1 \n                while len(s) == K:\n                    ans += r-i \n                    s[A[l]] -= 1 \n                    if s[A[l]] == 0: del s[A[l]] \n                    l += 1 \n        return ans
[]