Understanding the Problem
We are given an array of integers nums
and an integer k
. Our task is to find how many subarrays (continuous sequences of elements) contain exactly k
different integers.
This is not about finding the subarrays — it's about counting how many there are. For example, if nums = [1,2,1,2,3]
and k = 2
, we want to count all the subarrays that contain exactly 2 different numbers.
Subarrays must be contiguous. So, [1,2] is valid, but [1,3] is not if they’re not next to each other.
Step-by-Step Solution with Example
step 1: Understand the approach
We will use the sliding window technique with two pointers (left
and right
) and a frequency map to track the number of unique integers in the current window.
To count exactly k
unique elements, we cleverly compute:
exactlyK = atMostK(k) - atMostK(k - 1)
This works because atMostK(k)
includes all subarrays with up to k unique values, and atMostK(k-1)
removes those with fewer than k.
step 2: Create a helper function atMostK(nums, k)
This function counts how many subarrays have at most k
different numbers.
We initialize:
left = 0
right = 0
(looping pointer)
count = 0
(result)
freq = {}
(a map to count frequencies of numbers)
step 3: Slide the window using two pointers
We move the right
pointer one step at a time, and for each new number:
- Increase its count in the frequency map
- If it’s a new number (not seen before), decrease k
Then, if the number of unique elements exceeds k, we shrink the window from the left
until we have ≤ k unique elements again.
step 4: Count valid subarrays
At each step, the number of valid subarrays ending at right
is:
right - left + 1
This is because all subarrays starting from left
to right
are valid.
step 5: Return result using the difference formula
Now, the final answer becomes:
subarraysWithKDistinct(nums, k) = atMostK(nums, k) - atMostK(nums, k - 1)
step 6: Let's walk through the given example
Input: nums = [1,2,1,2,3], k = 2
atMostK(2)
→ Counts subarrays with ≤ 2 unique integers
atMostK(1)
→ Counts subarrays with ≤ 1 unique integer
Result = atMostK(2) - atMostK(1) = 10 - 3 = 7
The 7 valid subarrays with exactly 2 different integers are:
- [1,2]
- [2,1]
- [1,2]
- [2,3]
- [1,2,1]
- [2,1,2]
- [1,2,3]
Edge Cases
- Empty array:
nums = []
→ Result is 0
- k is 0: → No subarray can have 0 distinct elements
- k larger than number of unique elements in nums: → Result is 0
- All elements same:
nums = [1,1,1], k = 1
→ Counts all possible subarrays
Final Thoughts
This problem teaches a powerful trick: if you can count “at most k” and “at most k - 1,” you can derive “exactly k.”
The two-pointer (sliding window) technique is not just efficient — it's intuitive once you understand how to track a valid window and how to expand and shrink it.
By walking through the example and thinking in terms of subarray ranges, even a beginner can confidently build this logic step by step.
Comments
Loading comments...