I knew sliding window was the right move but fumbled the part where you shrink from the left while keeping the distinct count at exactly k.
Use a sliding window (two-pointer) technique to maintain a window with at most k distinct numbers, expanding the right pointer and shrinking the left pointer when the distinct count exceeds k. Track the minimum window length whenever the distinct count equals k. If no such window is found, return -1.
Pro tip: Clarify edge cases upfront (e.g., k=0, k > distinct elements, empty array) and discuss time/space complexity (O(n) time, O(k) space) to demonstrate thoroughness.
Confirm constraints: array size, possible values, and k. Handle edge cases like k=0 or k > total distinct elements by returning -1 immediately.
Use two pointers (left, right) and a hash map to count frequencies of elements in the current window. Initialize min_length to infinity.
Move right pointer to include new elements. While distinct count > k, move left pointer to shrink window. When distinct count == k, update min_length.
After traversal, if min_length is still infinity, return -1; otherwise return min_length.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.