← Questions

Shortest subarray with at least k distinct values

0
GoogleUberMicrosoftCodingLast asked Apr 2026

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^5
  • 1 <= arr[i] <= 10^5
  • 1 <= 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 = 1 simply 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 k distinct 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 k distinct 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 k distinct values.
  • Find the longest subarray with at most k distinct values.
  • Find the shortest window with exactly k distinct 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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding