Minimum Length Subarray with At Least K Distinct Elements
viaLeetCode
Problem Find the minimum length of a contiguous subarray containing at least K distinct elements; return -1 (or 0) if the whole array has fewer than K distinct values.
Input / Output
- Input: int array nums, int K. Output: min window length or -1.
Constraints
- n up to 10^5; O(n) two-pointer expected.
Example
- nums = [1,2,2,3,1], K = 3 → 3 ([2,3,1] or [1,2,..3] — the tightest is [2,3,1]).
Expected approach
- Sliding window: extend right, adding to a frequency map; once distinct >= K, shrink from the left while the condition still holds, updating the best length at each valid state. "At least K" is monotone in window growth, so the window logic is clean (contrast with exactly-K). O(n) time, O(K) space. Edge: total distinct < K → -1.
asked …