Shortest Window Holding Exactly k Different Values
Arrays & HashingAuto-graded · 24 test casesLast updated
Find the shortest contiguous slice of an integer list containing exactly k different values, using a sliding window with frequency counts.
You are given a list of integers nums and an integer target_distinct. Look at all contiguous slices of nums and consider only those that contain exactly target_distinct different values. Return the length of the shortest such slice.
If no slice qualifies, return -1.
Definitions
- A slice is a run of consecutive elements of
nums; skipping elements is not allowed. - A slice has exactly
target_distinctdifferent values when the set of its values has precisely that many members. Repeated occurrences of a value count once.
Edge-case rules
- If
target_distinctis0(or negative), return-1. - If
numsis empty, return-1. - If
target_distinctis larger than the number of different values innums(including when it exceedslen(nums)), return-1.
Constraints
- Values in
numsmay be any integers: positive, negative, or zero, with duplicates allowed. target_distinctis an integer and may be zero or larger thanlen(nums).- Aim for
O(n)time andO(n)extra space, wheren = len(nums).
Examples
Example 1
Input: shortest_window_with_k_distinct([1, 2, 1, 3, 4, 2, 3], 2)
Output: 2
Example 2
Input: shortest_window_with_k_distinct([1, 1, 1], 1)
Output: 1
Example 3
Input: shortest_window_with_k_distinct([1, 2, 3, 4], 3)
Output: 3
Example 4
Input: shortest_window_with_k_distinct([1, 2, 3], 0)
Output: -1
Hints
Hint 1
Think of a window [left, right] that you extend one element at a time on the right. Track how many times each value appears in the window with a dictionary.
Hint 2
If the window ever holds more than the target number of different values, advance the left edge until a value is fully removed and the count is back to the target.
Hint 3
To get the shortest window ending at the current right edge, also advance the left edge while the value it points at appears more than once in the window, since dropping it does not lose a distinct value. Record the length whenever the distinct count equals the target.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sweep a window [left, right] across the list, moving right one step at a time, and keep a dictionary of how many times each value occurs inside the window.
For each new right:
- Add
nums[right]to the counts. - If the window now has more than
target_distinctdifferent values, moveleftforward, decrementing counts and deleting a value when its count reaches zero, until the number of different values is back totarget_distinct. - Then trim redundant elements on the left: while the value at
leftoccurs more than once in the window, remove it and advanceleft. This does not change the number of different values but makes the window as short as possible for thisright. - If the window has exactly
target_distinctdifferent values, update the best length withright - left + 1.
The early exits handle the edge cases: a non-positive target, an empty list, or a target greater than len(nums) immediately return -1. If the target exceeds the number of different values actually present, the window never reaches that count and best stays unset, so -1 is returned.
Why it is correct
The shortest valid slice ends at some index right. For that right, the shortest valid slice starts at the largest left such that the window still contains exactly target_distinct values. Step 2 guarantees we never have too many values, using the smallest necessary shrink, and step 3 pushes left as far right as possible without losing any distinct value. So the window recorded at each right is the shortest valid slice ending there (if one exists), and taking the minimum over all right gives the global answer.
Complexity
Each of left and right only moves forward and passes each index at most once, so the time is O(n). The dictionary holds at most target_distinct + 1 entries, so extra space is O(n) in the worst case.
Reference solution
from typing import List
def shortest_window_with_k_distinct(nums: List[int], target_distinct: int) -> int:
if target_distinct <= 0 or not nums or target_distinct > len(nums):
return -1
counts = {}
left = 0
best = len(nums) + 1
for right, value in enumerate(nums):
counts[value] = counts.get(value, 0) + 1
# Too many distinct values: shrink until we are back to the target.
while len(counts) > target_distinct:
left_value = nums[left]
counts[left_value] -= 1
if counts[left_value] == 0:
del counts[left_value]
left += 1
# Drop redundant copies on the left without losing a distinct value.
while left <= right and counts[nums[left]] > 1:
left_value = nums[left]
counts[left_value] -= 1
left += 1
if len(counts) == target_distinct:
best = min(best, right - left + 1)
return -1 if best == len(nums) + 1 else best