LeetCode #992 Hard

Subarrays with K Different Integers

Subarrays with K Different Integers is LeetCode 992 (Hard). Given an integer array nums and an integer k, return how many contiguous subarrays contain exactly k different values.

  • Repeats are fine: [1, 2, 1] has 2 different values.
  • With up to 20,000 numbers, listing every subarray is too slow; the goal is O(n).
Constraints
  • 1 <= nums.length <= 2 * 10⁴
  • 1 <= nums[i], k <= nums.length
sliding-windowhashmaparray
Open on LeetCode ↗
02

Intuition

Fix where a subarray ends. Moving its start to the right can only drop values, never add them, so the starts that give at most m different values form one unbroken run that ends at the right end. A sliding window finds that run, and its length is the number of good subarrays ending there.

"Exactly k" has no such simple run: the good starts sit in a band whose left edge and right edge both move. So count the easy thing twice:

  • at most k counts every subarray with 1, 2, …, k values;
  • at most k − 1 counts the same ones except those with exactly k.

Their difference is exactly the subarrays with k values.

How to spot this pattern

Counting subarrays with exactly k distinct elements (or exactly k odd numbers, or a sum of exactly k) is usually at most k minus at most k − 1, because "at most" windows slide cleanly and "exactly" windows do not. Binary Subarrays With Sum and Count Number of Nice Subarrays use the same trick.

03

Approach

Try it first

Before reading on, fix the right end of a subarray and ask which start points give exactly k values. Is it one start, or a range? Then think about what is easier to count: exactly k, or at most k.

1

Write a helper that counts at most m kinds

Walk right over the array with a count map and a kinds counter. When a value's count goes from 0 to 1, a new kind has entered the window, so kinds goes up by one.

2

Shrink until the window is legal again

While kinds > m, lower the count of nums[left] and move left right; when a count drops to 0, that value has left the window, so kinds goes down. The window is now the longest legal one ending at right.

3

Add the window length

Every start from left to right gives a subarray with at most m kinds, so add right - left + 1. Each subarray is counted once, at the index where it ends.

4

Subtract the two counts

Return at_most(k) - at_most(k - 1). Subarrays with fewer than k kinds appear in both counts and cancel; only those with exactly k are left.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def subarraysWithKDistinct(self, nums: list[int], k: int) -> int:
▶3 def at_most(m: int) -> int:
▶4 count = {}
▶5 left = kinds = total = 0
▶6 for right, x in enumerate(nums):
▶7 count[x] = count.get(x, 0) + 1
▶8 if count[x] == 1:
▶9 kinds += 1
▶10 while kinds > m:
▶11 y = nums[left]
▶12 count[y] -= 1
▶13 if count[y] == 0:
▶14 kinds -= 1
▶15 left += 1
▶16 total += right - left + 1
▶17 return total
▶18 
▶19 return at_most(k) - at_most(k - 1)
nums12123L Rcounts1×1at most 2+1=at most 1=answer−=pass 1: 1 end here → add 1
passat most 2
window1starts that work
total1
Pass 1 counts subarrays with at most 2 different values. Every start from index 0 to 0 gives a subarray ending here with at most 2 kinds, so 1 subarray count.
nums12123LRcounts1×12×1at most 2+1+2=at most 1=answer−=2 end here → add 2
passat most 2
window2starts that work
total3
Every start from index 0 to 1 gives a subarray ending here with at most 2 kinds, so 2 subarrays count.
nums12123LRcounts1×22×1at most 2+1+2+3=at most 1=answer−=3 end here → add 3
passat most 2
window3starts that work
total6
Every start from index 0 to 2 gives a subarray ending here with at most 2 kinds, so 3 subarrays count.
nums12123LRcounts1×22×2at most 2+1+2+3+4=at most 1=answer−=4 end here → add 4
passat most 2
window4starts that work
total10
Every start from index 0 to 3 gives a subarray ending here with at most 2 kinds, so 4 subarrays count.
nums12123LRcounts1×22×23×1at most 2+1+2+3+4=at most 1=answer−=3 kinds, over 2 → shrink
passat most 2
kinds3limit 2
Adding 3 brings a new value into the window, which now holds 3 different values, more than the 2 this pass allows. The left edge has to move right until a whole kind is gone.
nums12123LRcounts1×12×23×1at most 2+1+2+3+4=at most 1=answer−=drop 1, another 1 remains
kinds3
left1
One 1 leaves, but another copy is still inside, so the window still has 3 kinds and must keep shrinking.
nums12123LRcounts1×12×13×1at most 2+1+2+3+4=at most 1=answer−=drop 2, another 2 remains
kinds3
left2
One 2 leaves, but another copy is still inside, so the window still has 3 kinds and must keep shrinking.
nums12123LRcounts2×13×1at most 2+1+2+3+4=at most 1=answer−=drop 1 → 2 kinds, legal
kinds2
left3
The last 1 leaves the window, so that kind is gone and the window has 2 kinds. It is legal again.
nums12123LRcounts2×13×1at most 2+1+2+3+4+2=12at most 1=answer−=2 end here → add 2, total 12
passat most 2
window2starts that work
total12
Every start from index 3 to 4 gives a subarray ending here with at most 2 kinds, so 2 subarrays count. This pass is done: 12 subarrays in all.
nums12123L Rcounts1×1at most 2+1+2+3+4+2=12at most 1+1=answer−=pass 2: 1 end here → add 1
passat most 1
window1starts that work
total1
Pass 2 counts subarrays with at most 1 different value. Every start from index 0 to 0 gives a subarray ending here with at most 1 kind, so 1 subarray count.
nums12123LRcounts1×12×1at most 2+1+2+3+4+2=12at most 1+1=answer−=2 kinds, over 1 → shrink
passat most 1
kinds2limit 1
Adding 2 brings a new value into the window, which now holds 2 different values, more than the 1 this pass allows. The left edge has to move right until a whole kind is gone.
nums12123L Rcounts2×1at most 2+1+2+3+4+2=12at most 1+1=answer−=drop 1 → 1 kinds, legal
kinds1
left1
The last 1 leaves the window, so that kind is gone and the window has 1 kind. It is legal again.
nums12123L Rcounts2×1at most 2+1+2+3+4+2=12at most 1+1+1=answer−=1 end here → add 1
passat most 1
window1starts that work
total2
Every start from index 1 to 1 gives a subarray ending here with at most 1 kind, so 1 subarray count.
nums12123LRcounts1×12×1at most 2+1+2+3+4+2=12at most 1+1+1=answer−=2 kinds, over 1 → shrink
passat most 1
kinds2limit 1
Adding 1 brings a new value into the window, which now holds 2 different values, more than the 1 this pass allows. The left edge has to move right until a whole kind is gone.
nums12123L Rcounts1×1at most 2+1+2+3+4+2=12at most 1+1+1=answer−=drop 2 → 1 kinds, legal
kinds1
left2
The last 2 leaves the window, so that kind is gone and the window has 1 kind. It is legal again.
nums12123L Rcounts1×1at most 2+1+2+3+4+2=12at most 1+1+1+1=answer−=1 end here → add 1
passat most 1
window1starts that work
total3
Every start from index 2 to 2 gives a subarray ending here with at most 1 kind, so 1 subarray count.
nums12123LRcounts1×12×1at most 2+1+2+3+4+2=12at most 1+1+1+1=answer−=2 kinds, over 1 → shrink
passat most 1
kinds2limit 1
Adding 2 brings a new value into the window, which now holds 2 different values, more than the 1 this pass allows. The left edge has to move right until a whole kind is gone.
nums12123L Rcounts2×1at most 2+1+2+3+4+2=12at most 1+1+1+1=answer−=drop 1 → 1 kinds, legal
kinds1
left3
The last 1 leaves the window, so that kind is gone and the window has 1 kind. It is legal again.
nums12123L Rcounts2×1at most 2+1+2+3+4+2=12at most 1+1+1+1+1=answer−=1 end here → add 1
passat most 1
window1starts that work
total4
Every start from index 3 to 3 gives a subarray ending here with at most 1 kind, so 1 subarray count.
nums12123LRcounts2×13×1at most 2+1+2+3+4+2=12at most 1+1+1+1+1=answer−=2 kinds, over 1 → shrink
passat most 1
kinds2limit 1
Adding 3 brings a new value into the window, which now holds 2 different values, more than the 1 this pass allows. The left edge has to move right until a whole kind is gone.
nums12123L Rcounts3×1at most 2+1+2+3+4+2=12at most 1+1+1+1+1=answer−=drop 2 → 1 kinds, legal
kinds1
left4
The last 2 leaves the window, so that kind is gone and the window has 1 kind. It is legal again.
nums12123L Rcounts3×1at most 2+1+2+3+4+2=12at most 1+1+1+1+1+1=5answer−=1 end here → add 1, total 5
passat most 1
window1starts that work
total5
Every start from index 4 to 4 gives a subarray ending here with at most 1 kind, so 1 subarray count. This pass is done: 5 subarrays in all.
nums12123at most 2+1+2+3+4+2=12at most 1+1+1+1+1+1=5answer12−5=7answer: 7
at most 212
at most 15
answer7
Subarrays with fewer than 2 kinds are in both totals and cancel. What is left, 12 − 5 = 7, is exactly the subarrays with 2 different values.
05

Common pitfalls

Adding 1 per right end instead of the window length

✗ Wrong
total += 1
✓ Right
total += right - left + 1

The window is the longest legal subarray ending at right, but every shorter one ending there is legal too. For [1, 2, 1, 2, 3], k = 2 both helper calls shrink to 5, and the answer comes out 0 instead of 7.

Measuring kinds with the map size without deleting zeros

✗ Wrong
count[y] -= 1
while len(count) > m: ...
✓ Right
count[y] -= 1
if count[y] == 0:
    del count[y]  # or keep a kinds counter

A value whose count fell to 0 is no longer in the window, but its key stays in the map. len(count) then never drops, the loop keeps shrinking past right until left runs off the end of the array: an IndexError for [1, 2, 1, 2, 3] with m = 1.

Trying to count exactly k with one window

✗ Wrong
if kinds == k:
    total += right - left + 1
✓ Right
return at_most(k) - at_most(k - 1)

Adding the window length whenever the window has k kinds also counts its shorter tails, which can have fewer kinds. For [1, 2, 1], k = 2 the window [1, 2, 1] adds 3, but its tail [1] has one kind, so the code returns 5 instead of 3.

06

Edge cases

k is more than the number of different values

No window ever has more than k - 1 kinds, so both helper calls count every subarray, and the difference is 0. The tracer's third example shows this.

k = 1

The second call is at_most(0): every new value forces the window empty, so it returns 0, and the answer is just the subarrays made of one repeated value.

07

Complexity

Time
O(n)
Space
O(n)
Each helper call moves left and right forward at most n times each, and it runs twice. Values are at most n, so a plain array of size n + 1 works as the count map.
08

Subarrays with K Different Integers FAQ

Can it be done in one pass?

Yes. Keep two left edges: one for the longest window with at most k kinds and one for at most k − 1. At each right end, the gap between them is the number of starts with exactly k kinds. It is the same O(n) idea folded into one loop, with two windows to maintain by hand.

Why is this rated Hard if the code is short?

The code is short once you see the subtraction. The hard part is noticing that exactly k cannot be slid directly, and that at most k minus at most k − 1 turns it into two easy problems.