Subarrays with K Different Integers

Given an integer array `nums` and an integer `k`, return the number of good subarrays of `nums`. A good array is an array where the number of different integers in that array is exactly `k`. For example, `[1,2,3,1,2]` has 3 different integers: 1, 2 and 3. A subarray is a contiguous part of an array.

30:00

Subarrays with K Different Integers
hard
Free written solution
Topics
Companies

Given an integer array nums and an integer k, return the number of good subarrays of nums.

A good array is an array where the number of different integers in that array is exactly k. For example, [1,2,3,1,2] has 3 different integers: 1, 2 and 3.

A subarray is a contiguous part of an array.

Example 1:
Input: {"nums":[1,2,1,2,3],"k":2}
Output: 7
Constraints:
  • 1≤nums.length≤2×1041 \leq \text{nums.length} \leq 2 \times 10^4

  • 1≤nums[i],k≤nums.length1 \leq \text{nums}[i], k \leq \text{nums.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,1,2,3],"k":2}

Keep the shortest window [left, right] with 2 distinct values. prefix counts the duplicates trimmed off its front, which are extra valid starts.

k = 2

1
2
1
2
3

0

1

2

3

4

distinct

-

prefix

-

res

0

Variables
VariableValue
k2
left0
prefix0
distinct0
res0
DepthFunction Call
Stack empty
0/14