DSA problem
Subarrays with K Different Integers
Given an integer array nums and an integer k, return the number of good subarrays of nums.
A good subarray is a contiguous subarray where the number of distinct integers in that subarray is exactly equal to k.
For example, [1, 2, 3, 1, 2] has exactly 3 distinct integers. A subarray is a contiguous, non-empty part of an array.
Counting subarrays with exactly k distinct integers directly is awkward because the constraint is not monotonic. The standard trick rewrites the answer as atMost(k) - atMost(k - 1), where atMost(x) counts subarrays with at most x distinct integers — a quantity that is monotonic and computable with a single linear sliding window.
Examples
nums = [1,2,1,2,3], k = 27nums = [1,2,1,3,4], k = 33nums = [2,2,2], k = 16Constraints
- 1 <= nums.length <= 2 * 10^4
- 1 <= nums[i], k <= nums.length
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.