Subarrays Distinct Element Sum of Squares II - Problem

Imagine you're analyzing the diversity of elements in every possible contiguous section of an array. Your task is to measure this diversity in a unique way!

Given a 0-indexed integer array nums, you need to:

  1. Find all possible subarrays - every contiguous sequence of elements
  2. Count distinct elements in each subarray
  3. Square these counts and sum them all up

For example, if a subarray [1, 2, 1] has 2 distinct elements (1 and 2), it contributes 2² = 4 to our final answer.

Return the sum modulo 10⁹ + 7 since the result can be extremely large.

Challenge: With arrays up to 10⁵ elements, a naive approach won't suffice - you'll need advanced data structures like Binary Indexed Trees or Segment Trees to efficiently track contribution changes as subarrays expand.

Input & Output

example_1.py — Simple Array
$ Input: nums = [1, 2, 1]
Output: 15
💡 Note: Subarray [1] has 1 distinct element: 1² = 1. Subarray [2] has 1 distinct element: 1² = 1. Subarray [1] has 1 distinct element: 1² = 1. Subarray [1,2] has 2 distinct elements: 2² = 4. Subarray [2,1] has 2 distinct elements: 2² = 4. Subarray [1,2,1] has 2 distinct elements: 2² = 4. Total: 1+1+1+4+4+4 = 15
example_2.py — All Same Elements
$ Input: nums = [2, 2, 2]
Output: 6
💡 Note: Every subarray has exactly 1 distinct element (the value 2). There are 6 subarrays total: [2], [2], [2], [2,2], [2,2], [2,2,2]. Each contributes 1² = 1 to the sum. Total: 6 × 1 = 6
example_3.py — All Different Elements
$ Input: nums = [1, 2, 3]
Output: 20
💡 Note: Subarrays: [1]=1², [2]=1², [3]=1², [1,2]=2², [2,3]=2², [1,2,3]=3². Total: 1+1+1+4+4+9 = 20

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • Result must be returned modulo 109 + 7

Visualization

Tap to expand
🏛️ Museum Gallery Diversity AnalysisRoom 1Art: MonetRoom 2Art: PicassoRoom 3Art: MonetRoom 4Art: Van GoghPath: 2² = 4Path: 2² = 4Path: 3² = 9BIT Tracking SystemPosition contributions:Room 1: 1² = 1Room 2: 1²+2² = 5Room 3: 1²+2²+2² = 9Room 4: 1²+2²+2²+3² = 18BIT enables O(log n) updates when artwork repeats in later rooms
Understanding the Visualization
1
Setup tracking system
Initialize BIT to efficiently track contribution changes
2
Process each room
As visitors enter each room, update diversity contributions
3
Handle revisits
When artwork repeats, adjust previous contributions
4
Calculate final score
Sum all squared diversity scores across all paths
Key Takeaway
🎯 Key Insight: Instead of recalculating diversity for every path, we incrementally track how each new room affects all existing paths, using BIT for efficient updates when artworks repeat.
Asked in
Google 23 Meta 18 Amazon 15 Microsoft 12
26.4K Views
Medium Frequency
~35 min Avg. Time
847 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