#2913
Subarrays Distinct Element Sum of Squares I
EasyArrayHash TableHash 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 solution uses a sliding window approach with a hashmap to efficiently track the frequency of elements in the current subarray, allowing us to calculate distinct counts without re-evaluating the entire subarray each time.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a hashmap to store the frequency of elements and two pointers for the sliding window.
- 2Step 2: Expand the right pointer to include new elements and update the frequency map.
- 3Step 3: For each new element added, calculate the distinct count and add its square to the total sum.
- 4Step 4: Move the left pointer to shrink the window and update the frequency map accordingly.
solution.py22 lines
1# Full working Python code
2
3def subarrayDistinctCountSumSquares(nums):
4 total_sum = 0
5 freq_map = {}
6 left = 0
7 n = len(nums)
8 for right in range(n):
9 freq_map[nums[right]] = freq_map.get(nums[right], 0) + 1
10 distinct_count = len(freq_map)
11 total_sum += distinct_count ** 2
12 while left <= right:
13 freq_map[nums[left]] -= 1
14 if freq_map[nums[left]] == 0:
15 del freq_map[nums[left]]
16 left += 1
17 distinct_count = len(freq_map)
18 total_sum += distinct_count ** 2
19 return total_sum
20
21# Example usage
22print(subarrayDistinctCountSumSquares([1, 2, 1])) # Output: 15ℹ
Complexity note: The time complexity is O(n) because we are using a sliding window to traverse the array only once, and the space complexity is O(n) due to the hashmap storing the frequency of elements.
- 1Understanding how to track distinct elements efficiently is crucial.
- 2Using a sliding window can significantly reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.