Quick Overview

Find the shortest contiguous subarray containing at least k distinct values. Practice sliding-window invariants, frequency maps, and linear-time minimization.

Shortest Subarray with at Least K Distinct Values

Company: Squarepoint

Role: Quantitative Researcher

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

Given an array `nums` of positive integers and an integer `k`, call a contiguous subarray **good** when it contains at least `k` distinct values. Implement: ```text min_good_subarray_length(nums: List[int], k: int) -> int ``` Return the minimum length of a good subarray. Return `-1` if no good subarray exists. ### Constraints - `1 <= len(nums) <= 200_000` - `1 <= nums[i] <= 10^9` - `1 <= k <= 200_000` - The target complexity is (O(n)) expected time and (O(d)) extra space, where (d) is the number of distinct values in the active window. ### Clarifications - The subarray must be contiguous. - “At least `k`” permits more than `k` distinct values. - Repeated occurrences count once toward the distinct-value total. ```hint Shrink every valid window Advance one boundary until the window becomes good, then move the other boundary as far as possible while it remains good. ``` ### Examples ```text Input: nums = [1, 2, 2, 3, 1], k = 3 Output: 3 Explanation: [2, 3, 1] has three distinct values. Input: nums = [5, 5, 5], k = 2 Output: -1 ``` ### Evaluation Focus - Correct maintenance of frequency and distinct-value counts. - Minimality across overlapping candidate windows. - Linear two-pointer behavior without restarting a scan for every left endpoint. ### Extension How would you count all subarrays containing at least `k` distinct values?

Quick Answer: Find the shortest contiguous subarray containing at least k distinct values. Practice sliding-window invariants, frequency maps, and linear-time minimization.

Given an array of positive integers nums and an integer k, call a contiguous subarray good when it contains at least k distinct values. Return the minimum length of a good subarray, or -1 if no good subarray exists.

Constraints

  • 1 <= nums.length <= 200000
  • 1 <= nums[i] <= 1000000000
  • 1 <= k <= 200000

Examples

Input: ([1, 2, 2, 3, 1], 3)

Expected Output: 3

Explanation: The source example's shortest qualifying window is [2, 3, 1].

Input: ([5, 5, 5], 2)

Expected Output: -1

Explanation: Only one distinct value exists, so no good subarray exists.

Hints

  1. Track the frequency of each value in the current contiguous window.
  2. Once the window has at least k distinct values, move its left boundary while it remains good.

Loading coding console...