I jumped straight to brute force and talked through the O(n^2) approach first, which was fine, but I fumbled a bit explaining why contracting the left pointer was safe while keeping the distinct count valid.
Use a sliding window (two pointers) to maintain a window with at most k distinct integers, expanding the right pointer and shrinking the left pointer when the distinct count reaches k. Track the minimum window length that contains exactly k distinct integers, and return -1 if no such window exists.
Pro tip: Clarify edge cases upfront (e.g., k > distinct elements in array, empty array) and discuss time/space complexity (O(n) time, O(k) space) to demonstrate thoroughness.
Restate the problem to ensure clarity. Identify edge cases: k <= 0, k > number of distinct elements, empty array, and array with all identical elements.
Explain that a sliding window with two pointers efficiently finds the shortest subarray by maintaining a window with at most k distinct integers.
Initialize left=0, a frequency map, and min_length=infinity. Expand right, update frequency, and while distinct count == k, update min_length and shrink from left.
After traversal, return min_length if found, else -1. State time complexity O(n) and space complexity O(k) due to the frequency map.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.