#992
Subarrays with K Different Integers
HardArrayHash TableSliding WindowCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use a sliding window approach to efficiently count subarrays with exactly k distinct integers. By maintaining two pointers and a frequency map, we can dynamically adjust the window size to ensure we have the exact number of distinct integers.
⚙️
Algorithm
3 steps- 1Step 1: Define a helper function to count subarrays with at most k distinct integers.
- 2Step 2: Use the helper function to count subarrays with at most k distinct integers and at most (k-1) distinct integers.
- 3Step 3: The result is the difference between the two counts, which gives us the count of subarrays with exactly k distinct integers.
solution.py18 lines
1def subarraysWithKDistinct(nums, k):
2 def atMostK(k):
3 count = 0
4 left = 0
5 freq = {}
6 for right in range(len(nums)):
7 if nums[right] in freq:
8 freq[nums[right]] += 1
9 else:
10 freq[nums[right]] = 1
11 while len(freq) > k:
12 freq[nums[left]] -= 1
13 if freq[nums[left]] == 0:
14 del freq[nums[left]]
15 left += 1
16 count += right - left + 1
17 return count
18 return atMostK(k) - atMostK(k - 1)ℹ
Complexity note: The time complexity is O(n) because we traverse the array with two pointers, and the space complexity is O(n) due to the frequency map that stores counts of elements.
- 1Using a sliding window allows us to efficiently count subarrays without generating all possible combinations.
- 2The difference between counts of at most k and at most (k-1) gives us the exact count of subarrays with exactly k distinct integers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.