1def subarrays_with_k_distinct(nums, k):
2 def at_most(k_val):
3 count = {}
4 left = 0; ans = 0
5 for right in range(len(nums)):
6 count[nums[right]] = count.get(nums[right], 0) + 1
7 while len(count) > k_val:
8 count[nums[left]] -= 1
9 if count[nums[left]] == 0: del count[nums[left]]
10 left += 1
11 ans += right - left + 1
12 return ans
13 return at_most(k) - at_most(k-1)