Subarrays with K Different Integers
Given an integer array nums and an integer k, a subarray is 'good' if it contains exactly k distinct integers. Return the number of good (contiguous) subarrays of nums.
Open official problem prompt ↗Count how many contiguous slices of the array hold precisely k different values — not fewer, not more.
Imagine counting playlists that use exactly 2 genres. It is hard to filter for 'exactly 2' directly, but easy to count 'at most 2 genres' and 'at most 1 genre'. Subtract the second from the first and you are left with playlists using exactly 2.
- Input
- nums = [1, 2, 1, 2, 3], k = 2
- Output
- 7
- Why
- The subarrays with exactly 2 distinct values are [1,2], [2,1], [1,2], [2,1], [1,2,1], [2,1,2], and [1,2,1,2] — seven of them.
1 <= nums.length <= 2 * 10^41 <= nums[i], k <= nums.length