Skip to content
RED SAGSkills

Stretches With Exactly K Distinct Values

Return the number of non-empty contiguous subarrays of nums that contain exactly k distinct values.

Example 1

Input: nums = [1, 2, 1, 2, 3], k = 2
Output: 7
Explanation: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2

Input: nums = [1, 2, 1, 3, 4], k = 3
Output: 3

Constraints

  • 0 <= nums.length <= 5 * 10^4
  • 1 <= k <= nums.length + 1
  • 1 <= nums[i] <= 10^9
Hint 1

"Exactly k" equals "at most k" minus "at most k - 1".

Hint 2

For "at most m", every right end contributes right - left + 1 subarrays from the shrinking window.

Good practice for: Data Scientist, Data Engineer, Machine Learning Engineer, AI Engineer (LLM & Generative AI), Backend Developer, Site Reliability Engineer

Run checks your code on 2 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.