Subarrays with K Different Integers
Hard
Topics
Given an integer array nums and an integer target (= k), return the number of contiguous subarrays that contain exactly target distinct integers.
Example 1
Input: nums = [1,2,1,2,3], target = 2 Output: 7
Example 2
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
- Write
atMost(m): slide a window keeping distinct values at mostm, addingr - l + 1at each step. - Return 0 for negative
m. - 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 7Complexity
- Time — O(n): two window passes, each moving both pointers forward at most
ntimes. - 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 whenkis 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)import java.util.*;
class Solution {
public int subarraysWithKDistinct(int[] nums, int target) {
return atMost(nums, target) - atMost(nums, target - 1);
}
private int atMost(int[] nums, int m) {
if (m < 0) return 0;
Map<Integer,Integer> cnt = new HashMap<>();
int l = 0, res = 0;
for (int r = 0; r < nums.length; r++) {
cnt.put(nums[r], cnt.getOrDefault(nums[r], 0) + 1);
while (cnt.size() > m) {
cnt.put(nums[l], cnt.get(nums[l]) - 1);
if (cnt.get(nums[l]) == 0) cnt.remove(nums[l]);
l++;
}
res += r - l + 1;
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int subarraysWithKDistinct(vector<int>& nums, int target) {
function<long long(int)> atMost = [&](int m) -> long long {
if (m < 0) return 0;
unordered_map<int,int> cnt;
int l = 0;
long long res = 0;
for (int r = 0; r < (int)nums.size(); r++) {
cnt[nums[r]]++;
while ((int)cnt.size() > m) {
if (--cnt[nums[l]] == 0) cnt.erase(nums[l]);
l++;
}
res += r - l + 1;
}
return res;
};
return (int)(atMost(target) - atMost(target - 1));
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var subarraysWithKDistinct = function(nums, target) {
const atMost = (m) => {
if (m < 0) return 0;
const cnt = new Map();
let l = 0, res = 0;
for (let r = 0; r < nums.length; r++) {
cnt.set(nums[r], (cnt.get(nums[r]) || 0) + 1);
while (cnt.size > m) {
cnt.set(nums[l], cnt.get(nums[l]) - 1);
if (cnt.get(nums[l]) === 0) cnt.delete(nums[l]);
l++;
}
res += r - l + 1;
}
return res;
};
return atMost(target) - atMost(target - 1);
};