Subarrays with K Different Integers

Hard

Topics
ArrayHash TableSliding WindowCounting

Given an integer array nums and an integer target (= k), return the number of contiguous subarrays that contain exactly target distinct integers.

Example 1

1021122334
Input:  nums = [1,2,1,2,3], target = 2
Output: 7

Example 2

1021123344
Input:  nums = [1,2,1,3,4], target = 3
Output: 3

Constraints

  • 1 <= nums.length <= 2*10^4
  • 1 <= nums[i] <= nums.length
  • 1 <= target <= nums.length
Editorial — intuition, approach, complexity and pitfalls

Intuition

Counting subarrays with exactly k distinct values is awkward with a sliding window, because the window invariant "at most k" is monotone while "exactly k" is not — you cannot shrink toward it.

The standard move is to express it as a difference: exactly(k) = atMost(k) - atMost(k-1). Every subarray with at most k distinct values either has at most k-1 or has exactly k, so subtracting leaves precisely the ones wanted.

And atMost(m) is a clean sliding window. Extend the right edge, shrink the left while the distinct count exceeds m, and add r - l + 1 — the number of subarrays ending at r that stay within the window.

Approach

  1. Write atMost(m): slide a window keeping distinct values at most m, adding r - l + 1 at each step.
  2. Return 0 for negative m.
  3. Answer atMost(k) - atMost(k-1).

Dry Run

nums = [1,2,1,2,3]   k = 2

atMost(2)
  r  l  subarrays ending at r  running total
  0  0  1                      1
  1  0  2                      3
  2  0  3                      6
  3  0  4                      10
  4  3  2                      12

atMost(1)
  r  l  subarrays ending at r  running total
  0  0  1                      1
  1  1  1                      2
  2  2  1                      3
  3  3  1                      4
  4  4  1                      5

exactly(2) = 12 - 5 = 7

answer 7

Complexity

  • Time — O(n): two window passes, each moving both pointers forward at most n times.
  • Space — O(n) for the counting map in the worst case of all-distinct values.

Common Pitfalls

  • Trying to maintain "exactly k" directly with one window. There is no monotone shrink condition, and attempts to patch it end up double counting.
  • Adding 1 per window rather than r - l + 1. Every suffix of the current window is a distinct qualifying subarray.
  • Forgetting to delete a key when its count reaches zero, so len(cnt) keeps counting values no longer in the window and the shrink loop never terminates correctly.
  • Omitting the guard for m < 0, reached when k is 1 in some formulations.
  • Computing atMost(k) - atMost(k-1) with two separate maps left over from each other. Each call must start fresh.
  • Reaching for the three-pointer variant that tracks the leftmost and second-leftmost window bounds. It is a single-pass O(n) alternative and it is correct, but it is markedly harder to get right than the subtraction.

Full Solution — all languages

class Solution:
    def subarraysWithKDistinct(self, nums, target):
        def at_most(m):
            if m < 0:
                return 0
            cnt = {}
            l = 0
            res = 0
            for r in range(len(nums)):
                cnt[nums[r]] = cnt.get(nums[r], 0) + 1
                while len(cnt) > m:
                    cnt[nums[l]] -= 1
                    if cnt[nums[l]] == 0:
                        del cnt[nums[l]]
                    l += 1
                res += r - l + 1
            return res
        return at_most(target) - at_most(target - 1)
Asked at Capital One Roblox
SensAI
Beta
Tap the mic to stop voice mode