Problem
You are given an array nums
consisting of positive integers.
We call a subarray of an array complete if the following condition is satisfied:
- The number of distinct elements in the subarray is equal to the number of distinct elements in the whole array.
Return the number of complete subarrays.
A subarray is a contiguous non-empty part of an array.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 2000
Solution
Method 1 - Using sliding window
We need to count the number of complete subarrays in the array nums
.
- A subarray is complete if the count of distinct elements in it equals the count of distinct elements in the entire array
nums
. - To solve this problem, the sliding window technique with hashing can be used efficiently. The sliding window allows us to dynamically validate subarrays while avoiding unnecessary computations.
Approach
- Compute the number of distinct elements in the array
nums
using a set. Let’s call this valuetotal_distinct
. - Use a sliding window strategy to traverse possible subarrays. Maintain a hash map (or dictionary) to keep track of the frequency of elements within the window.
- For each valid subarray (with
total_distinct
elements), increment the count of complete subarrays. - Iterate over all possible subarray starting points using the above technique.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. The computation of distinct elements in the array takesO(n)
using a set.- The sliding window approach also traverses the array once, yielding
O(n)
overall.
- The sliding window approach also traverses the array once, yielding
- 🧺 Space complexity:
O(n)
. The hash map/dictionary can hold up ton
elements in the worst case (if all elements are unique).