Subarrays with K Different Integers - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1,2,3], k = 2
Output: 7
💡 Note: Subarrays with exactly 2 distinct integers: [1,2], [2,1], [1,2], [2,1,2], [1,2,3], [2,3], [1,3]. Total count = 7.
Example 2 — Single Distinct
$ Input: nums = [1,2,1,3,4], k = 3
Output: 3
💡 Note: Subarrays with exactly 3 distinct integers: [1,2,1,3], [2,1,3], [1,3,4]. Total count = 3.
Example 3 — All Same Elements
$ Input: nums = [1,1,1,1], k = 1
Output: 10
💡 Note: All subarrays have exactly 1 distinct integer. With n=4, total subarrays = n*(n+1)/2 = 4*5/2 = 10.

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • 1 ≤ nums[i], k ≤ nums.length

Visualization

Tap to expand
Subarrays with K=2 Different Integers12123Input Array[1,2] ✓[2,1] ✓[1,2] ✓[2,1,2] ✓[1,2,3] ✓[2,3] ✓[1,3] ✓Valid Subarrays (exactly 2 distinct)Total Count: 7
Understanding the Visualization
1
Input
Array [1,2,1,2,3] with k=2
2
Process
Find all subarrays with exactly 2 distinct integers
3
Output
Count = 7 subarrays
Key Takeaway
🎯 Key Insight: Transform 'exactly k' into the difference between 'at most k' and 'at most k-1'
Asked in
Google 15 Facebook 12 Amazon 8
89.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen