KatInterview

Shortest Subarray with K Unique Values

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingsliding-windowtwo-pointershash-table

Last updated

Find the minimum length of a contiguous subarray containing at least K unique elements using a sliding window.

Given an integer array a and a target integer k, determine the length of the shortest contiguous subarray that contains at least k distinct values.

If no such contiguous subarray exists in a, return 0.

Constraints

  • 1 <= len(a) <= 10^5
  • 1 <= a[i] <= 10^5
  • 1 <= k <= 10^5

Examples

Example 1

Input: shortest_subarray_with_k_distinct([1, 2, 1, 2, 3], 2)

Output: 2

Example 2

Input: shortest_subarray_with_k_distinct([1, 2, 1, 3], 3)

Output: 3

Hints

Hint 1

Try using a sliding window (two pointers) to keep track of a contiguous dynamic range.

Hint 2

Maintain a frequency map of elements in the current range to count how many distinct integers are currently present.

Hint 3

When the current window has at least k distinct integers, record its length and shrink the window from the left to see if a smaller valid subarray exists.