Subarrays with K Different Integers hard
Description
Given an integer array nums and an integer k, return the number of good subarrays of nums. A good subarray is a contiguous subarray with exactly k different integers.
Examples
> Case 1:
nums = [1, 2, 1, 2, 3], k = 2
Output: 7
Explanation:
[1, 2], [2, 1], [1, 2], [2, 3],
[1, 2, 1], [2, 1, 2], [1, 2, 1, 2]
> Case 2:
nums = [1, 2, 1, 3, 4], k = 3
Output: 3Constraints
1 <= nums.length <= 2 × 10^41 <= nums[i], k <= nums.length
Why direct sliding window doesn’t work
Sliding window naturally answers “longest” / “shortest” / “first” / “at most K” questions. For “exactly K,” the window can drift past K back to K-1 and forward to K+1 — there’s no natural place to record a count of “exactly-K windows ending here.”
The clean indirection: solve “exactly K” as at most K minus at most K−1, both of which ARE clean sliding-window problems.
State design
Define:
atMost(K) = number of contiguous subarrays with at most K distinct integers.Then:
exactly(K) = atMost(K) - atMost(K - 1)For atMost(K):
- Shape: variable-size, longest-valid-style. State: frequency map.
- Shrink while:
len(freq) > K. - Count contribution: every valid window contributes
r − l + 1(every subarray ending atrand starting at>= lis valid).
Code
Time: O(n) — two linear passes plus a subtraction.
Space: O(k).
Why r − l + 1 per valid window? When the window [l..r] is valid (at-most-K distinct), so is every smaller right-aligned window: [l..r], [l+1..r], …, [r..r]. That’s r − l + 1 subarrays ending at r. Sum across all r and you’ve counted every at-most-K subarray exactly once.
Analysis
- Time:
O(n). - Space:
O(k).
Same skin (every “exactly K” with a monotone counting property)
- Count Number of Nice Subarrays —
atMost(k) − atMost(k − 1)on count of odd integers. - Binary Subarrays With Sum — same trick on a binary sum.
- Subarrays with K Different Integers (this problem) — the canonical example.
If you ever see “exactly K … in a contiguous subarray,” try at-most-K first. If the “at most” version is monotone, you’re done in 12 lines.