292. Subarrays with K Different Integers

You are given an integer array nums and an integer k.

Return the number of good subarrays of nums.

A good subarray is defined as a contiguous subarray of nums that contains exactly k distinct integers.

A subarray is a contiguous part of the array.

Example 1:

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

Output: 7  

Explanation: The 7 subarrays with exactly 2 different integers are:  

[1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]

Example 2:

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

Output: 3  

Explanation: The 3 subarrays with exactly 3 different integers are:  

[1,2,1,3], [2,1,3], [1,3,4]

Now Your Turn!

Pick the correct output for the given input

Input: nums = [1, 1, 1, 1], k = 1  

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 <= 2 * 104

1 <= nums[i], k <= nums.length

Fun Facts

0
class Solution {
public:
int subarraysWithKDistinct(vector<int>& nums, int k) {
// Your code goes here
}
};
Test Case

Input:

K
Nums