My first instinct was to think about longest subarray problems I'd seen before, and I almost went down the wrong path.
Use a sliding window (two pointers) to maintain a window with at most k distinct integers, expanding the right pointer and shrinking the left when the distinct count exceeds k. Track the minimum length whenever the window contains exactly k distinct integers. If no such window exists, return -1.
Pro tip: Clarify edge cases upfront (e.g., k > distinct elements, empty array) and mention that the sliding window approach is optimal for this problem because it avoids redundant checks and runs in O(n) time.
Restate the problem: find the shortest contiguous subarray with at least k distinct integers. Discuss edge cases: k <= 0, k > total distinct elements, empty array, and duplicates.
Select sliding window (two pointers) because it efficiently finds subarrays with a constraint on distinct elements. Explain why brute force is inefficient (O(n^2) or worse).
Maintain a frequency map for elements in the window. Expand right pointer, add element to map. While distinct count > k, shrink from left. When distinct count == k, update minimum length.
After traversal, if minimum length is still infinity, return -1. Otherwise, return the minimum length found.
State time complexity O(n) and space O(k) for the frequency map. Walk through a small example to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.