Subarrays with K Different Integers⚓︎
Description⚓︎
Given an integer array nums
and an integer k
, return the number of good subarrays of nums
.
A good array is an array where the number of different integers in that array 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 an array.
Example 1:
- Input:
nums = [1,2,1,2,3], k = 2
- Output:
7
- Explanation:
Subarrays formed with exactly 2 different integers: [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:
Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
Constraints:
1 <= nums.length <= 2 * 10^4
1 <= nums[i], k <= nums.length
Solution⚓︎
Code with comments:
Explanation:
The solution relies on a sliding window approach to count subarrays with at most K
distinct integers, encapsulated in the numOfMostKDistinct
function. The main idea is to maintain a window [left, right]
that satisfies the condition of having at most K
distinct integers. This is achieved by incrementing right
to expand the window and incrementing left
to shrink the window whenever the condition is violated (i.e., when the number of distinct integers exceeds K
).
For each position of right
, the solution counts how many subarrays ending at right
meet the criteria by calculating the difference right - left + 1
. This effectively counts all valid subarrays that include nums[right]
.
To find the number of subarrays with exactly K
distinct integers, the solution exploits a clever trick: it calculates the number of subarrays with at most K
distinct integers and subtracts from it the number of subarrays with at most K-1
distinct integers. This subtraction removes all subarrays that have fewer than K
distinct integers, leaving only those with exactly K
distinct integers.
This technique simplifies the problem by converting it from counting subarrays with "exactly" to "at most" K
distinct integers, which is easier to manage using a sliding window approach.