Subarrays Distinct Element Sum of Squares II - Problem

You are given a 0-indexed integer array nums. The distinct count of a subarray is defined as follows:

Let nums[i..j] be a subarray of nums consisting of all indices from i to j such that 0 <= i <= j < nums.length. The number of distinct values in nums[i..j] is called the distinct count of nums[i..j].

Return the sum of squares of distinct counts of all subarrays of nums. Since the answer may be very large, return it modulo 10^9 + 7.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1]
Output: 15
💡 Note: All subarrays: [1](1²=1), [2](1²=1), [1](1²=1), [1,2](2²=4), [2,1](2²=4), [1,2,1](2²=4). Sum = 1+1+1+4+4+4 = 15
Example 2 — All Different
$ Input: nums = [1,2]
Output: 6
💡 Note: Subarrays: [1](1²=1), [2](1²=1), [1,2](2²=4). Sum = 1+1+4 = 6
Example 3 — Single Element
$ Input: nums = [5]
Output: 1
💡 Note: Only one subarray [5] with 1 distinct element: 1² = 1

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Subarrays Distinct Element Sum of Squares II INPUT nums = [1, 2, 1] 1 i=0 2 i=1 1 i=2 All Subarrays: [1] distinct=1 [2] distinct=1 [1] distinct=1 [1,2] distinct=2 [2,1] distinct=2 [1,2,1] distinct=2 6 total subarrays ALGORITHM STEPS 1 Track Last Occurrence Use map to store last index of each element 2 Segment Tree Update Range add +1 for new distinct contribution 3 Sum of Squares Maintain sum of d(i)^2 using lazy propagation 4 Accumulate Results Add query result to total, modulo 10^9+7 Squares Calculation: 1^2 + 1^2 + 1^2 = 3 2^2 + 2^2 + 2^2 = 12 Total: 3 + 12 = 15 FINAL RESULT Output: 15 Breakdown: [1] : 1^2 = 1 [2] : 1^2 = 1 [1] : 1^2 = 1 [1,2] : 2^2 = 4 [2,1] : 2^2 = 4 [1,2,1] : 2^2 = 4 Sum = 15 OK - Verified Key Insight: Use Segment Tree with lazy propagation to efficiently track distinct counts. When element appears, add +1 to range [last_occurrence+1, current_index]. Maintain sum of squares: (d+1)^2 - d^2 = 2d + 1, enabling O(n log n) solution. TutorialsPoint - Subarrays Distinct Element Sum of Squares II | Set Tracking + Segment Tree Approach
Asked in
Google 25 Microsoft 20 Amazon 15
24.9K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen