Given an integer array nums and an integer k, return the number of good subarrays of nums.
A good subarray is a subarray in which the number of different integers is exactly k. For example, [1,2,3,1,2] has 3 different integers: 1, 2 and 3.
A subarray is a contiguous part of the array.
Function Signature
def subarrays_with_k_distinct(nums: list[int], k: int) -> int:
Rules
-
A subarray is contiguous and non-empty.
-
Subarrays are counted by position. Two subarrays that hold the same values at different positions count as two; in Example 1,
[1,2]
is counted twice.
Constraints
-
1 <= len(nums) <= 2 * 10^4
-
1 <= nums[i] <= len(nums)
-
1 <= k <= len(nums)
Examples
Input: nums = [1,2,1,2,3], k = 2
Output: 7
The subarrays with exactly 2 different integers are [1,2], [2,1], [1,2], [2,1,2], [1,2,1], [1,2,1,2] and [2,3], so the total is 7.
Input: nums = [1,2,1,3,4], k = 3
Output: 3
The subarrays with exactly 3 different integers are [1,2,1,3], [2,1,3] and [1,3,4]. Any longer window contains all four values.
Input: nums = [1,1,2], k = 3
Output: 0
The whole array holds only 2 different values, so no subarray can have 3.