[LeetCode] Count Subarrays With K Distinct Integers

3859. Count Subarrays With K Distinct Integers

You are given an integer array nums and two integers k and m.

Return an integer denoting the count of subarrays of nums such that:

  • The subarray contains exactly k distinct integers.
  • Within the subarray, each distinct integer appears at least m times.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
long long countSubarrays(vector<int>& nums, int k, int m) {
long long res = 0, l = 0, r = 0, n = nums.size(), pop = -1, over = 0;
unordered_map<int,int> freq;
auto add = [&](int idx) {
int x = nums[idx];
if(++freq[x] == m) over++;
};
auto del = [&](int idx) {
int x = nums[idx];
if(freq[x] == m) over--;
if(--freq[x] == 0) {
pop = idx;
freq.erase(x);
}
};
while(r < n) {
add(r++);
while(freq.size() > k) del(l++);
while(over == k and freq[nums[l]] > m) del(l++);
if(over == k) res += (l - pop);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/count-subarrays-with-k-distinct-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.