Adobe Coding Question: Shortest Subarray with K Distinct
Question Description
Problem overview
You are given an integer array nums and an integer k. Implement a function that returns the minimum length of a contiguous subarray that contains exactly k distinct integers. If no such subarray exists, return 0.
What you'll be asked to do
You should describe a linear-time approach using a sliding-window (two-pointer) pattern plus a hash table (frequency map). Walk through expanding the right pointer until your window includes k distinct values, then move the left pointer forward to shrink the window while still keeping exactly k distinct values — updating the minimum length whenever the window contains exactly k distinct integers.
Interview flow / stages
- Clarify edge cases (k == 0, k > number of distinct values in the whole array, empty array).
- Propose the sliding-window + hashmap plan and state time/space complexity.
- Implement carefully, explaining how you maintain counts and when you update the answer.
- Discuss correctness and test on small examples and corner cases.
Skill signals the interviewer is looking for
- Mastery of sliding-window and two-pointer techniques
- Correct use of hash maps to track frequencies and distinct counts
- Ability to reason about edge cases and complexity (aim for O(n) time and O(min(n, alphabet)) space)
- Clear incremental testing and explanation of why the shrink/expand steps maintain correctness
Try writing a clear, bug-free implementation you can walk through on a whiteboard or in a shared editor.
Common Follow-up Questions
- •Modify your function to return the actual shortest subarray (start and end indices) with exactly k distinct integers — how does that change your implementation?
- •How would you adapt the approach to find the longest contiguous subarray with exactly k distinct integers? What changes to shrinking logic are required?
- •If nums is a stream (you cannot store the whole array), can you still find the shortest subarray with exactly k distinct elements? Discuss trade-offs and possible approximations.
- •What if you must find the shortest subarray with at least k distinct integers rather than exactly k — how does the algorithm simplify?
- •How does the solution change if elements have weights and you need the minimum total weight subarray containing exactly k distinct values?
Related Questions
Explore More Questions
Practice This Question with AI
Get real-time hints, detailed requirements, and insightful analysis of the question.