KatInterview

Tightest Window Covering K Different Values

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingsliding-windowtwo-pointershash-map

Last 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^5
  • 1 <= readings[i] <= 10^5
  • 1 <= k <= 10^5
  • The function must return a single integer: the minimum block length, or -1 if no block qualifies.
  • When k exceeds the number of unique values in the whole list, the answer is -1.
  • When k == 1, the answer is 1, 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'.