Subarrays with K Different Integers

Count subarrays with exactly K distinct integers — atMost(K) − atMost(K−1).

Hard
Time O(n) Space O(n)
LeetCode
4 min read
sliding-window hash-map

Problem#

Return the number of contiguous subarrays of nums containing exactly k distinct integers.

Examples#

  • nums = [1,2,1,2,3], k = 27
  • nums = [1,2,1,3,4], k = 33

Constraints#

  • 1 <= nums.length, k <= nums.length.

Hints#

Hint 1
exactly(K) = atMost(K) − atMost(K−1). Each atMost is a clean variable window.

Approach#

Implement atMost(K) = number of subarrays with at most K distinct integers using the variable-window template. The exact count is the difference.

Solution#

Subarrays with K Different Integers
class Solution {
public:
int subarraysWithKDistinct(vector<int>& nums, int k) {
return atMost(nums, k) - atMost(nums, k - 1);
}
private:
int atMost(vector<int>& nums, int k) {
if (k < 0) return 0;
unordered_map<int,int> freq;
int left = 0, count = 0;
for (int right = 0; right < (int)nums.size(); ++right) {
++freq[nums[right]];
while ((int)freq.size() > k) {
if (--freq[nums[left]] == 0) freq.erase(nums[left]);
++left;
}
count += right - left + 1; // # of subarrays ending at `right` with ≤ k distinct
}
return count;
}
};

Editorial#

The “count subarrays ending at right” trick is the elegance: for each right, the number of valid starting points is exactly right - left + 1. The exact-vs-at-most reduction is a workhorse for any “exactly K” counting problem — usually the at-most version has a clean sliding window while the exact version doesn’t.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.