SDE & MLE Prep

992. Subarrays with K Different Integers

Problem

Count the contiguous subarrays of nums that contain exactly k distinct values.

Example: nums = [1,2,1,2,3], k = 2 → 7

Constraints: n ≤ 2·10⁴.

"Exactly k" is not monotonic, but "at most k" is: exactly(k) = atMost(k) − atMost(k−1). atMost counts, for each right end, the r − l + 1 valid windows.

Complexity: O(n).

class Solution:
    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
        def at_most(k):
            cnt = defaultdict(int)
            l = res = 0
            for r, x in enumerate(nums):
                cnt[x] += 1
                while len(cnt) > k:
                    cnt[nums[l]] -= 1
                    if cnt[nums[l]] == 0:
                        del cnt[nums[l]]
                    l += 1
                res += r - l + 1
            return res

        return at_most(k) - at_most(k - 1)