Tightest Window Covering K Different Values
Arrays & HashingAuto-graded · 20 test casesLast updated
Find the minimum length of a contiguous block of an integer list containing at least k different values, using a sliding window with a frequency map.
You are given a list of positive integers readings and an integer k. Consider every contiguous, non-empty block of readings. Your task is to find the length of the shortest block in which at least k different values appear.
If no block has at least k different values, return -1.
A block's "different values" count is the number of unique integers inside it, ignoring repeats. For example, the block [4, 4, 7] has 2 different values.
Constraints
1 <= len(readings) <= 10^51 <= readings[i] <= 10^51 <= k <= 10^5- The function must return a single integer: the minimum block length, or
-1if no block qualifies. - When
kexceeds the number of unique values in the whole list, the answer is-1. - When
k == 1, the answer is1, because the list is non-empty.
Examples
Example 1
Input: shortest_block_with_k_unique([1, 2, 1, 2, 3], 2)
Output: 2
Example 2
Input: shortest_block_with_k_unique([1, 2, 1, 3], 3)
Output: 3
Hints
Hint 1
Brute force over all blocks is quadratic. Think about what happens to the number of unique values when you extend a block on the right: it can never decrease.
Hint 2
Keep a window [left, right] with a dictionary of counts and a running tally of unique values. Move right one step at a time and update the tally when a count goes from 0 to 1.
Hint 3
Whenever the window has at least k unique values, record its length and then advance left as far as possible, using a while loop, updating the tally when a count drops to 0. Use a sentinel larger than n for 'not found'.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a sliding window with two pointers and a frequency dictionary.
- Move
rightacross the list, adding each value to the window. When a value's count goes from 0 to 1, increase theuniquetally. - While the window holds at least
kunique values, it is valid. Record its length, then remove the element atleft. If that value's count falls to 0, delete it from the dictionary and decreaseunique. Then advanceleft. - At the end, return
-1if nothing was recorded (the best length is still the sentineln + 1), otherwise return the best length.
Why it works
Extending a block to the right never removes a unique value, so validity is monotone in right. For a fixed right, the shrinking loop stops exactly when the window drops below k unique values. The last window recorded just before that is the one with the largest valid start index, which is the shortest valid block ending at right. Start positions that left passes are never needed again: for any later right, a block starting earlier would be longer than one starting at left - 1 or later that is still valid. Every valid block ends at some right, so taking the minimum over all right gives the global answer.
Using while rather than if is essential, as several elements may need to be removed. Deleting zero-count keys keeps the tally accurate.
Complexity
- Time: O(n). Each index enters the window once and leaves at most once, and dictionary operations are O(1) on average.
- Space: O(min(n, k)), since the dictionary never holds more than
kkeys after shrinking.
Reference solution
from typing import List
def shortest_block_with_k_unique(readings: List[int], k: int) -> int:
counts = {}
left = 0
unique = 0
n = len(readings)
best = n + 1
for right, value in enumerate(readings):
if counts.get(value, 0) == 0:
unique += 1
counts[value] = counts.get(value, 0) + 1
while unique >= k:
best = min(best, right - left + 1)
out_value = readings[left]
counts[out_value] -= 1
if counts[out_value] == 0:
del counts[out_value]
unique -= 1
left += 1
return -1 if best == n + 1 else best