Subarrays with K Different Integers

Hard

Description

Given an integer array nums and an integer k, return the number of contiguous subarrays that contain exactly k different integers.

Examples

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

7 subarrays with exactly 2 distinct integers.

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

Edge case with a single-element array.

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

Only 3 subarrays contain exactly 3 distinct integers: [1,2,1,3] (positions 0-3), [2,1,3,2] (positions 1-4), and [1,3,2,1] (positions 2-5). Each contains the distinct integers {1,2,3}. Other subarrays have fewer than 3 distinct integers.

Constraints

  • 1 ≤ nums.length ≤ 2 * 10⁴
  • 1 ≤ k ≤ nums.length

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!