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).
- 1 <= nums.length <= 2 * 10⁴
- 1 <= nums[i], k <= nums.length
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.
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.
Approach
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.
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Adding 1 per right end instead of the window length
total += 1
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
count[y] -= 1 while len(count) > m: ...
count[y] -= 1
if count[y] == 0:
del count[y] # or keep a kinds counterA 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
if kinds == k:
total += right - left + 1return 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.
Edge cases
k is more than the number of different valuesNo 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 = 1The 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.
Complexity
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.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.