Shortest subarray with at least k distinct values
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Uber's online assessment and at Google and Microsoft, last asked Apr 2026. It tests sliding window, two pointers and hash map.
You are given an integer array arr and an integer k. Call a contiguous subarray good if it contains at least k different values.
Return the length of the shortest good subarray. If no subarray is good, return -1.
Implement:
def shortest_good_subarray(arr: list[int], k: int) -> int: ...
Constraints
1 <= len(arr) <= 10^51 <= arr[i] <= 10^51 <= k <= len(arr)
Example 1
arr = [4, 4, 7, 4, 9, 7], k = 3
output: 3
The window [4, 9, 7] holds three different values. No window of length 2 can.
Example 2
arr = [5, 5, 5], k = 2
output: -1
The array has only one distinct value, so no subarray is good.
Aim for a solution faster than checking every subarray.
Clarifying questions
- Is
k = 1simply length 1? - Should I return only the length, or also the window?
- Are values bounded so I can use an array of counts instead of a dict?
What a strong answer covers
- Uses a two-pointer sliding window with a count per value and a distinct counter.
- Extends the right end; while the window has at least
kdistinct values, records its length and shrinks from the left. - Runs in O(n) time with O(distinct) memory, against O(n^2) or worse for checking every subarray.
- Returns -1 when the array has fewer than
kdistinct values (Example 2). - Tests the examples,
k = 1,k = len(arr)with all distinct values, and arrays with long runs of one value.
Follow-ups
- Count the subarrays with at least
kdistinct values. - Find the longest subarray with at most
kdistinct values. - Find the shortest window with exactly
kdistinct values.
Where it's asked
- Uber · Online assessment · Last asked Apr 202690 min · Two problems on a HackerRank-based platform, camera and screen share on · No AI
- Google · First round: coding · Last asked Jan 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
- Microsoft · Coding · Last asked Nov 202560 min · Ten to fifteen minutes of behavioral questions, then coding in HackerRank where you write a main and make the tests pass; usually three rounds · No AI unless the interviewer invites it; some 2026 loops add a round where you bring your own AI agent
What it tests
sliding window · two pointers · hash map
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.


