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 exactlykdistinct integers.
Within the subarray, each distinct integer appears at leastm times.
Example 1:
Input:nums = [1,2,1,2,2], k = 2, m = 2
Output:2
Explanation:
The possible subarrays with k = 2 distinct integers, each appearing at least m = 2 times are:
Subarray
Distinct numbers
Frequency
[1, 2, 1, 2]
{1, 2} → 2
{1: 2, 2: 2}
[1, 2, 1, 2, 2]
{1, 2} → 2
{1: 2, 2: 3}
Thus, the answer is 2.
Example 2:
Input:nums = [3,1,2,4], k = 2, m = 1
Output:3
Explanation:
The possible subarrays with k = 2 distinct integers, each appearing at least m = 1 times are:
Subarray
Distinct numbers
Frequency
[3, 1]
{3, 1} → 2
{3: 1, 1: 1}
[1, 2]
{1, 2} → 2
{1: 1, 2: 1}
[2, 4]
{2, 4} → 2
{2: 1, 4: 1}
Thus, the answer is 3.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= k, m <= nums.length
Solutions
Solution 1
Thinking
A subarray must contain exactly \(k\) distinct values, each appearing at least \(m\) times. \(n \le 10^5\) forbids enumerating intervals.
Exactly \(k\) kinds equals at least \(k\) minus at least \(k+1\), together with a window constraint that at least \(k\) values have frequency \(m\).
Two pointers track distinct count and how many values have reached \(m\). Once both \(\textit{lim}\) kinds and \(t \ge k\) hold, move the left end. Every start before that left end is valid.