Minimum Length Subarray with At Least K Distinct Elements

Problem Find the minimum length of a contiguous subarray containing at least K distinct elements; return -1 (or 0) if the whole array has fewer than K distinct values.

Input / Output

  • Input: int array nums, int K. Output: min window length or -1.

Constraints

  • n up to 10^5; O(n) two-pointer expected.

Example

  • nums = [1,2,2,3,1], K = 3 → 3 (the tightest window with 3 distinct values is [2,3,1]).
asked …
LeaderboardSalaryAccount