My first instinct was brute force and I kind of just said it out loud before thinking, which wasn't a great look.
Use a sliding window (two-pointer) technique to maintain a window that contains at least k distinct integers. Expand the right pointer to include more elements, and once the window is valid, shrink from the left to find the shortest valid window. Track the minimum length throughout.
Pro tip: Clarify edge cases upfront, such as when k is greater than the total number of distinct integers in the array, and mention that the algorithm runs in O(n) time with O(k) space, which is optimal.
Restate the problem to ensure clarity. Discuss edge cases: empty array, k <= 0, k > total distinct elements, and arrays with all identical elements.
Explain that a brute-force solution would be O(n^2) or worse, and that a sliding window efficiently finds the shortest subarray by maintaining a window with at least k distinct integers.
Use a hash map to count frequencies of elements in the window. Expand right pointer to add elements until the window has at least k distinct integers. Then, shrink from the left while the window remains valid to minimize length.
After each shrink, update the minimum length if the current window is valid and shorter. Continue until the right pointer reaches the end.
If no valid window is found, return -1. Otherwise, return the minimum length. State that time complexity is O(n) and space complexity is O(k) due to the hash map.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.