Subarrays with K Different Integers
Master this topic with zero to advance depth.
Subarrays with K Different Integers
Count the number of 'good' subarrays where the number of different integers is exactly k.
Visual Representation
nums = [1, 2, 1, 2, 3], k = 2
Exactly(K) = AtMost(K) - AtMost(K-1)
AtMost(2) Subarrays: [1], [2], [1,2], [1,2,1], [2,1,2] ...
AtMost(1) Subarrays: [1], [2], [1], [2], [3]
Exactly(2) = 12 - 5 = 7Examples
Level I: Brute Force
Intuition
Iterate through all possible substrings nums[i...j]. For each substring, count the number of unique integers. If the count is exactly k, increment the total result.
Thought Process
- Outer loop
ifrom0ton-1. - Inner loop
jfromiton-1. - Maintain a set of unique elements encountered so far in
nums[i...j]. - If
set.size() == k,res++. - If
set.size() > k, break inner loop (since distinct elements only increase).
Detailed Dry Run
| i | j | Subarray | Distinct | Result |
|---|---|---|---|---|
| 0 | 0 | [1] | 1 | 0 |
| 0 | 1 | [1, 2] | 2 | 1 |
| 0 | 2 | [1, 2, 1] | 2 | 2 |
| 0 | 4 | [1, 2, 1, 2, 3] | 3 | STOP |
Level II: Sliding Window with 3 Pointers (O(N))
Intuition
We can use three pointers to find the number of subarrays with exactly k distinct integers directly. We maintain two 'left' pointers: left1 (minimum index to satisfy k distinct) and left2 (minimum index to satisfy k-1 distinct). The number of valid subarrays ending at right is left2 - left1.
Thought Process
- Maintain
count1(frequencies forleft1) andcount2(frequencies forleft2). - As we expand
right, update both maps. - Move
left1as far as possible such that the window[left1, right]haskdistinct elements. - Move
left2as far as possible such that the window[left2, right]hask-1distinct elements. - For each
right, any start index in the range[left1, left2)produces a valid subarray.
Pattern: Multi-pointer Sliding Window
Level III: Optimal (Sliding Window - Two Pass)
Intuition
Thought Process
Finding 'exactly K' is difficult with a single sliding window because shrinking doesn't always reduce the count of distinct elements. However, finding 'at most K' is a standard sliding window problem. Using the property Exactly(K) = AtMost(K) - AtMost(K-1) simplifies the problem significantly.
Patterns
- Complement Rule:
Exactly(K) = AtMost(K) - AtMost(K-1). - Frequency Map: Track counts of each number in the current window.
Detailed Dry Run
| X | AtMost(X) |
|---|---|
| 2 | 12 |
| 1 | 5 |
| Result | 12 - 5 = 7 |
⚠️ Common Pitfalls & Tips
Be careful with the count map logic. Incrementing AtMost(K) means counting ALL subarrays with distinct elements.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.