Python coding

Count runs with exactly k distinct values

Given a list of integers nums and an integer k >= 1, count the contiguous, non-empty subarrays that contain exactly k different values. Subarrays at different positions count separately, even when they hold the same values: for [1, 2, 1] and k = 2 the answer is 3 ([1, 2], [2, 1] and [1, 2, 1]).

nums may be empty. Aim for O(n) time.

Besides the tests, one large input (4,000 values) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • count_exact_distinct([3,3,5,3], 2) → 5
  • count_exact_distinct([4,4,4], 1) → 6
  • count_exact_distinct([1,2,3,1,2], 3) → 6
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Exactly k is not monotonic: widening a window can make it valid or invalid. At most k distinct is: shrinking a window never adds a value.

Hint 2

For at most k: keep value counts, shrink while more than k values are present, then add right - left + 1, the valid subarrays ending at right.

Hint 3

Exactly k = atMost(k) − atMost(k − 1): two linear passes. atMost(0) is 0.

Solution and why it works
pythonO(n) · O(k)
def count_exact_distinct(nums: list[int], k: int) -> int:
    def at_most(limit: int) -> int:      # subarrays with at most `limit` distinct values
        count = {}
        left = total = 0
        for right, x in enumerate(nums):
            count[x] = count.get(x, 0) + 1
            while len(count) > limit:
                y = nums[left]
                count[y] -= 1
                if count[y] == 0:
                    del count[y]
                left += 1
            total += right - left + 1    # every start from left to right is valid
        return total

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

Windows with at most k distinct values are monotonic: shrinking never adds a value. So after shrinking to at most k values, all right - left + 1 subarrays ending at right qualify. Exactly k is atMost(k) − atMost(k − 1): two O(n) passes instead of O(n²) subarrays. The trap is adding 1 per step for a window held at exactly k values: that counts only the longest valid subarray at each right edge and misses the shorter ones that start later.

Related lab: Sliding window, step by step