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 Different Integers INPUT Array nums: 1 i=0 2 i=1 1 i=2 2 i=3 3 i=4 k = 2 Valid Subarrays (k=2): [1,2] [2,1] [1,2] [2,3] [1,2,1] [2,1,2] [1,2,1,2] ALGORITHM STEPS 1 Sliding Window Trick exact(k) = atMost(k) - atMost(k-1) 2 atMost(k) Function Count subarrays with <= k distinct 3 Two Pointers Expand right, shrink left 4 Count Subarrays Add (right - left + 1) each step atMost(2) = 12 atMost(1) = 5 exact(2) = 12 - 5 = 7 HashMap tracks element counts {1:count, 2:count} FINAL RESULT Output: 7 7 good subarrays found All Valid Subarrays: [1,2] [1,2,1] [2,1] [2,1,2] [1,2] [1,2,1,2] [2,3] Complexity: Time: O(n) Space: O(k) Key Insight: Convert "exactly K" problem to "at most K" using subtraction: exact(k) = atMost(k) - atMost(k-1). The sliding window with hashmap counts subarrays ending at each position with at most K distinct elements. This transformation enables efficient O(n) solution using two-pointer technique. TutorialsPoint - Subarrays with K Different Integers | Optimal Solution (Sliding Window)
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