Count Subarrays With K Distinct Integers

Given an integer array nums and two integers k and m.

Determine the number of contiguous subarrays where exactly k unique elements exist, and each of these unique elements occurs a minimum of m times within that chosen subarray.

Example 1:

Input: nums = [4, 4, 4, 5, 5, 6], k = 2, m = 2

Output: 2

Explanation:

The valid subarrays must contain exactly 2 unique numbers, and both must appear at least twice. The valid subarrays are: [4, 4, 5, 5]: Contains {4, 5}, with 4 appearing twice and 5 appearing twice. [4, 4, 4, 5, 5]: Contains {4, 5}, with 4 appearing three times and 5 appearing twice.

Example 2:

Input: nums = [1, 2, 3], k = 1, m = 1

Output: 3

Explanation:

We need subarrays with exactly 1 unique integer appearing at least once. The valid subarrays are the individual single-element subarrays: [1], [2], and [3].

Now Your Turn!

Pick the correct output for the given input

Input: nums = [2, 2, 3, 3], k = 2, m = 2

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105
  • 1 <= k, m <= nums.length

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
long long countSubarrays(vector<int>& nums, int k, int m) {
}
};
Test Case

Input:

K
M
Nums