Find shortest subarray with ≥k distinct integers
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of array algorithms, handling of distinct-element counting, and the ability to design time- and space-efficient solutions for constrained subarray queries.
Constraints
- 1 <= len(nums) <= 2 * 10^5
- 1 <= k <= len(nums)
- -10^9 <= nums[i] <= 10^9
Examples
Input: ([1, 2, 1, 3, 4], 3)
Expected Output: 3
Explanation: The shortest valid subarrays are [2, 1, 3] and [1, 3, 4], both of length 3.
Input: ([1, 1, 1], 2)
Expected Output: -1
Explanation: There is only 1 distinct integer in the entire array, so reaching 2 distinct integers is impossible.
Input: ([5, 5, 5, 5], 1)
Expected Output: 1
Explanation: Any single-element subarray already contains at least 1 distinct integer.
Input: ([], 1)
Expected Output: -1
Explanation: An empty array has no non-empty subarray, so the requirement cannot be met.
Input: ([1, 2, 2, 3, 1], 2)
Expected Output: 2
Explanation: A shortest valid subarray is [1, 2] or [2, 3], both with 2 distinct integers and length 2.
Input: ([4, -1, 4, -1, 2], 3)
Expected Output: 3
Explanation: The subarray [4, -1, 2] contains 3 distinct integers and has length 3, which is minimal.
Input: ([7, 8], 0)
Expected Output: 0
Explanation: With k = 0, the empty subarray already satisfies the condition.
Hints
- Use a sliding window and keep track of the frequency of each value inside the current window.
- Whenever the window has at least `k` distinct values, try shrinking it from the left to make it as short as possible.