Shortest Subarray with K Unique Values
Arrays & HashingAuto-graded · 18 test casesLast 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^51 <= a[i] <= 10^51 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem can be solved efficiently using a sliding window (two-pointer) approach combined with a frequency hash table.
- Maintain two pointers,
leftandright, representing the bounds of the current subarray window. - Advance
rightstep by step through the arraya, insertinga[right]into a hash map tracking element counts within the window. - Track the number of distinct elements inside the current window.
- Whenever the number of distinct elements reaches or exceeds
k:- Update the global minimum length seen so far (
right - left + 1). - Increment
leftto shrink the window from the left side, updating the element counts and distinct count accordingly, until the window is no longer valid.
- Update the global minimum length seen so far (
- If no valid subarray is ever found during the process, return
0.
Correctness
The sliding window approach works because adding elements to a window can only maintain or increase the number of distinct elements, never decrease it. Therefore:
- Extending the right bound helps satisfy the condition ($\ge k$ distinct values).
- Once satisfied, advancing the left bound tests shorter valid subarrays ending at the current
right. - Since both pointers move exclusively forward, every minimal valid subarray ending at each index
rightis evaluated, guaranteeing that the global minimum length is found.
Complexity Analysis
- Time Complexity: $O(n)$ where $n$ is the length of
a. Each element is added byrightonce and removed byleftat most once. Hash map additions and removals take $O(1)$ average time. - Space Complexity: $O(\min(n, U))$, where $U$ is the number of distinct values in
a, used by the frequency map to store counts of elements currently inside the window.
from typing import List
def shortest_subarray_with_k_distinct(a: List[int], k: int) -> int:
counts = {}
left = 0
distinct_count = 0
min_length = len(a) + 1
for right, val in enumerate(a):
if counts.get(val, 0) == 0:
distinct_count += 1
counts[val] = counts.get(val, 0) + 1
while distinct_count >= k:
min_length = min(min_length, right - left + 1)
left_val = a[left]
counts[left_val] -= 1
if counts[left_val] == 0:
distinct_count -= 1
del counts[left_val]
left += 1
return 0 if min_length > len(a) else min_length