Started with brute force because I panicked a little and needed to say something.
Use a sliding window (two-pointer) technique to maintain a window that contains at most k distinct integers, and whenever the window has exactly k distinct integers, shrink it from the left to find the shortest valid subarray. Track the minimum length seen. If no such subarray exists, return -1.
Pro tip: Clarify edge cases upfront: if k is greater than the number of distinct integers in the array, return -1 immediately. Also, discuss time and space complexity (O(n) time, O(k) space) to demonstrate efficiency awareness.
Restate the problem to ensure clarity. Identify edge cases: k <= 0, k > distinct count, empty array, and array length less than k.
Select sliding window with a hash map to track frequencies of elements in the current window. This allows O(n) time by expanding and shrinking the window dynamically.
Initialize left and right pointers, a frequency map, and a counter for distinct elements. Expand right, update map, and when distinct count equals k, shrink left while maintaining k distinct, updating the minimum length.
After iterating through the array, if no valid window was found, return -1; otherwise, return the minimum length recorded.
State time complexity O(n) and space complexity O(k). Walk through a small example to verify correctness, and consider potential optimizations or alternative approaches.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.