#2916

Subarrays Distinct Element Sum of Squares II

Hard
ArrayDynamic ProgrammingBinary Indexed TreeSegment TreeHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a sliding window approach combined with a frequency map to efficiently count distinct elements in subarrays. This reduces the need for nested loops and allows us to compute the result in linear time.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a frequency map to count occurrences of elements and variables to track the total sum and the current distinct count.
  2. 2Step 2: Use a single loop to iterate through the array, treating each index as the end of the current subarray.
  3. 3Step 3: For each new element added to the subarray, update the frequency map and adjust the distinct count accordingly.
  4. 4Step 4: For each position, calculate the sum of squares of distinct counts from the current subarray and add it to the total sum.
  5. 5Step 5: Return the total sum modulo 10^9 + 7.
solution.py31 lines
1# Full working Python code
2
3def sum_of_squares(nums):
4    MOD = 10**9 + 7
5    total_sum = 0
6    freq = {}
7    distinct_count = 0
8    n = len(nums)
9
10    left = 0
11    for right in range(n):
12        if nums[right] in freq:
13            freq[nums[right]] += 1
14        else:
15            freq[nums[right]] = 1
16            distinct_count += 1
17
18        total_sum += distinct_count ** 2
19        total_sum %= MOD
20
21        while left <= right and freq[nums[left]] > 1:
22            freq[nums[left]] -= 1
23            if freq[nums[left]] == 0:
24                del freq[nums[left]]
25                distinct_count -= 1
26            left += 1
27
28    return total_sum
29
30# Example usage
31print(sum_of_squares([1, 2, 1]))  # Output: 15

Complexity note: The time complexity is O(n) because we process each element in the array once. The space complexity is O(n) due to the frequency map that stores counts of elements.

  • 1Using a frequency map allows for efficient counting of distinct elements.
  • 2Sliding window techniques can reduce the time complexity significantly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.