Subarrays with K Different Integers (LeetCode 992): Solution and Explanation
Given an integer array and k, count the contiguous subarrays that contain exactly k different values.
Intuition
Fix the right end of a subarray. As the start moves left, the number of different values can only grow, so the starts that give exactly k form one contiguous range.
The right edge of that range is the start of the shortest window ending at right that still holds k different values. Call it left. The value at left has exactly one copy in the window, otherwise we could drop it.
Every duplicate we trimmed off the front to reach that shortest window is also a valid start, because removing it did not change the set of values. Count those in prefix; the right end then adds prefix + 1 subarrays.
When a new value pushes the window to k + 1 different values, the value at left (one copy) must go, and every old extra start would contain it, so prefix resets to 0.
Approach: Sliding window with a prefix of extra starts
- Keep a count array,
left = prefix = distinct = res = 0. - For each
right, addnums[right]to the counts and increasedistinctif it is new. - If
distinct > k, removenums[left], moveleft, decreasedistinct, and setprefix = 0. - While the value at
lefthas more than one copy in the window, remove it, moveleft, and increaseprefix. - If
distinct == k, addprefix + 1tores. Returnresat the end.
Step-by-step example
nums = [1,2,1,2,3], k = 2
- right = 0: window [1], one distinct value, nothing counted.
- right = 1: window [1,2] has 2 distinct. The 1 at index 0 has one copy, so no trim. Add 1, res = 1.
- right = 2: another 1 arrives. Now the 1 at index 0 has two copies, so trim it: left = 1, prefix = 1. Window [2,1], add 2, res = 3.
- right = 3: another 2. The 2 at index 1 is now duplicated, so trim it: left = 2, prefix = 2. Window [1,2], add 3, res = 6.
- right = 4: 3 makes 3 distinct. Drop the 1 at index 2 and reset prefix to 0. Window [2,3], add 1, res = 7.
Code: Python, Java, C++
1class Solution:
2 def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
3 count = [0] * (len(nums) + 1)
4 left = prefix = distinct = res = 0
5 for right in range(len(nums)):
6 count[nums[right]] += 1
7 if count[nums[right]] == 1:
8 distinct += 1
9 if distinct > k:
10 count[nums[left]] -= 1
11 left += 1
12 distinct -= 1
13 prefix = 0
14 while count[nums[left]] > 1:
15 count[nums[left]] -= 1
16 left += 1
17 prefix += 1
18 if distinct == k:
19 res += prefix + 1
20 return res1class Solution {
2 public int subarraysWithKDistinct(int[] nums, int k) {
3 int[] count = new int[nums.length + 1];
4 int left = 0, prefix = 0, distinct = 0, res = 0;
5 for (int right = 0; right < nums.length; right++) {
6 if (count[nums[right]]++ == 0) {
7 distinct++;
8 }
9 if (distinct > k) {
10 count[nums[left++]]--;
11 distinct--;
12 prefix = 0;
13 }
14 while (count[nums[left]] > 1) {
15 count[nums[left++]]--;
16 prefix++;
17 }
18 if (distinct == k) {
19 res += prefix + 1;
20 }
21 }
22 return res;
23 }
24}1class Solution {
2public:
3 int subarraysWithKDistinct(vector<int>& nums, int k) {
4 vector<int> count(nums.size() + 1, 0);
5 int left = 0, prefix = 0, distinct = 0, res = 0;
6 for (int right = 0; right < (int)nums.size(); right++) {
7 if (count[nums[right]]++ == 0) {
8 distinct++;
9 }
10 if (distinct > k) {
11 count[nums[left++]]--;
12 distinct--;
13 prefix = 0;
14 }
15 while (count[nums[left]] > 1) {
16 count[nums[left++]]--;
17 prefix++;
18 }
19 if (distinct == k) {
20 res += prefix + 1;
21 }
22 }
23 return res;
24 }
25};Time and space complexity
O(n)
right visits each index once and left only moves forward, so each element enters and leaves the window at most once.
O(n)
The count array has n + 1 slots because every value is between 1 and n.
Other approaches
At most k minus at most k - 1 (time O(n), space O(n))
Write a helper that counts subarrays with at most g distinct values using one shrinking window (add right - left + 1 per right end). The answer is atMost(k) - atMost(k - 1). Easier to prove, but two passes.
Check every start (time O(n^2), space O(n))
For each start, extend the end with a set of seen values and count the ends where the set size is exactly k, stopping once it passes k.
Common mistakes
- Using a single shrinking window and adding 1 per right end. That only counts the shortest good subarray and misses the starts covered by duplicates.
- Forgetting to reset
prefixwhen a new value forces an eviction. Those old starts all contain the evicted value. - Trying to compute exactly k as a single at-most window. You need either the subtraction trick or the extra-starts counter.
- Using a hash map when the values are bounded by n. An array is faster and avoids hashing overhead.
Frequently asked questions
Why must the value at left have exactly one copy?
The while loop removes the front element as long as it appears again later in the window. When it stops, the front value is unique in the window, so removing it would drop the distinct count below k.
Is the one-pass version really better than atMost(k) - atMost(k - 1)?
Both are O(n). The subtraction trick is easier to explain and less error prone; the one-pass version saves a second scan. Either is a strong interview answer.
Can the answer overflow a 32-bit integer?
No. The total number of subarrays is at most n(n+1)/2, about 2 * 10^8 for n = 2 * 10^4, which fits.
What happens when k is larger than the number of different values?
distinct never reaches k, so nothing is ever added and the answer is 0.