KatInterview

Shortest Window Holding Exactly k Different Values

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashingsliding-windowhash-mapsubarray

Last 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_distinct different values when the set of its values has precisely that many members. Repeated occurrences of a value count once.

Edge-case rules

  • If target_distinct is 0 (or negative), return -1.
  • If nums is empty, return -1.
  • If target_distinct is larger than the number of different values in nums (including when it exceeds len(nums)), return -1.

Constraints

  • Values in nums may be any integers: positive, negative, or zero, with duplicates allowed.
  • target_distinct is an integer and may be zero or larger than len(nums).
  • Aim for O(n) time and O(n) extra space, where n = 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.