← 返回 ibm 的题目列表Minimum Length Subarray with K Distinct Numbers
类型:qbank
Given an integer list and `k`, return the minimum subarray length containing exactly or at least `k` distinct numbers, or `-1` when no such subarray exists.
Requirements
Function: getMinLengthSubarray(arr, k).
Input: List<Integer> arr and integer k.
Output: minimum qualifying subarray length, or -1 if no qualifying subarray exists.
The prompt centres on maintaining a num -> frequency map with a sliding window.
Notes
Expand the right pointer and update the frequency map and distinct count.
While the current window satisfies the distinct-count condition, update the best length and shrink from the left.
Clarify whether the condition is exactly k distinct or at least k distinct. The sliding-window skeleton is the same, but the shrink condition differs slightly.
Preparation
Code the at-least-k variant first: expand right, then shrink while the window remains valid, updating the minimum length before each shrink.
Prepare a one-sentence clarification for exactly-k vs at-least-k; if it is exactly k, shrink when distinct exceeds k and update only when distinct equals k.