I jumped straight to a sliding window and got something working for 'at least k' before realizing the question said 'exactly.' Had to backtrack and rethink the shrink logic.
Use a sliding window (two-pointer) technique to maintain a window with at most k distinct integers, and when the window has exactly k distinct, try to shrink it from the left to find the minimum length. Track the minimum length seen and return -1 if no valid window exists.
Pro tip: Clarify edge cases upfront (e.g., k <= 0, k > distinct elements) and mention that the sliding window approach runs in O(n) time, which is optimal for this problem.
Restate the problem to ensure clarity: find the smallest contiguous subarray with exactly k distinct integers. Discuss edge cases such as k <= 0, k greater than the number of distinct elements in the array, or empty array.
Explain that a brute-force solution would be O(n^2) or worse, so a sliding window (two-pointer) technique is optimal. Maintain a window [left, right] and a frequency map of elements in the window.
Expand the right pointer to include new elements. When the window contains exactly k distinct integers, update the minimum length and then shrink from the left while maintaining exactly k distinct integers to find the smallest valid window.
Keep a variable to store the minimum length found. After processing all possible windows, return the minimum length or -1 if no valid window was found.
State that the time complexity is O(n) because each element is added and removed at most once, and space complexity is 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.