InferenceAI

Enter at least two characters to search.

Start free

Exactly K Distinct Subarrays

hardSliding Window40 min50 XP

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

Requirements

  • O(n)O(n) using: exactly(k)=atMost(k)−atMost(k−1)\text{exactly}(k) = \text{atMost}(k) - \text{atMost}(k - 1).

Examples

EXAMPLE WALKTHROUGHclassic

A guided view of the published example, not a trace of your code.

INPUT[[1,2,1,2,3],2]
TASKexactly_k_distinct_subarrays()
EXPECTED OUTPUT7

Start with the input values shown in this example.

Example 1 of 3

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

Output: 7

Explanation: classic

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

Output: 3

Explanation: three distinct

Input: nums = [1,1,1], k = 1

Output: 6

Explanation: all same

Hint 1

Counting subarrays with at most k distinct values is a standard sliding window: each right end adds (right - left + 1).

Topics

DSASliding WindowPython