#2799
Count Complete Subarrays in an Array
MediumArrayHash TableSliding WindowHash 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)
The optimal approach uses a sliding window technique to efficiently count complete subarrays. Instead of checking every subarray, we expand and contract our window to maintain the required number of distinct elements.
⚙️
Algorithm
4 steps- 1Step 1: Use a hashmap to count occurrences of elements in the current window.
- 2Step 2: Expand the window by moving the end pointer and adding elements to the hashmap.
- 3Step 3: When the number of distinct elements matches the total distinct count, count all valid subarrays ending at the current end pointer.
- 4Step 4: Contract the window from the start until the number of distinct elements is less than required.
solution.py28 lines
1# Full working Python code
2
3def count_complete_subarrays(nums):
4 total_distinct = len(set(nums))
5 count = 0
6 left = 0
7 freq_map = {}
8 distinct_count = 0
9
10 for right in range(len(nums)):
11 if nums[right] in freq_map:
12 freq_map[nums[right]] += 1
13 else:
14 freq_map[nums[right]] = 1
15 distinct_count += 1
16
17 while distinct_count == total_distinct:
18 count += len(nums) - right
19 freq_map[nums[left]] -= 1
20 if freq_map[nums[left]] == 0:
21 del freq_map[nums[left]]
22 distinct_count -= 1
23 left += 1
24
25 return count
26
27# Example usage
28print(count_complete_subarrays([1, 3, 1, 2, 2])) # Output: 4ℹ
Complexity note: The time complexity is O(n) because each element is processed at most twice (once when expanding and once when contracting the window). The space complexity is O(n) due to the hashmap storing the frequency of elements.
- 1Understanding distinct elements is crucial to solving the problem.
- 2Using a sliding window approach is more efficient than brute force for counting subarrays.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.