Subarrays Distinct Element Sum of Squares I - Problem
Subarray Analysis: You are given a 0-indexed integer array nums. Your task is to analyze all possible subarrays and calculate a special metric based on their distinct elements.

For each subarray nums[i..j] (where 0 ≤ i ≤ j < nums.length), you need to:
1. Count the number of distinct values in that subarray
2. Square that count
3. Add it to your final result

Goal: Return the sum of squares of distinct counts for all possible subarrays.

Example: For [1,2,1], subarrays are [1], [2], [1], [1,2], [2,1], [1,2,1] with distinct counts 1, 1, 1, 2, 2, 2. Sum of squares = 1² + 1² + 1² + 2² + 2² + 2² = 15.

Input & Output

example_1.py — Basic Case
$ Input: [1,2,1]
Output: 15
💡 Note: Subarrays: [1](distinct=1,square=1), [2](distinct=1,square=1), [1](distinct=1,square=1), [1,2](distinct=2,square=4), [2,1](distinct=2,square=4), [1,2,1](distinct=2,square=4). Total: 1+1+1+4+4+4=15
example_2.py — All Same Elements
$ Input: [1,1,1]
Output: 6
💡 Note: All subarrays have exactly 1 distinct element. There are 6 subarrays total: [1], [1], [1], [1,1], [1,1], [1,1,1]. Each contributes 1² = 1, so total is 6.
example_3.py — All Different Elements
$ Input: [1,2,3]
Output: 20
💡 Note: Subarrays: [1](1²=1), [2](1²=1), [3](1²=1), [1,2](2²=4), [2,3](2²=4), [1,2,3](3²=9). Total: 1+1+1+4+4+9=20

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100
  • The result will fit in a 32-bit integer

Visualization

Tap to expand
Library Shelf Analysis: Measuring Book Genre DiversitySci-FiRomanceMysterySci-FiAnalysis Process:Section [0]: 1 genre → 1² = 1Section [0,1]: 2 genres → 2² = 4Section [0,1,2]: 3 genres → 3² = 9Section [0,1,2,3]: 3 genres → 3² = 9Key Insight:• Squaring emphasizes sections with more diversity• Use hash set to efficiently track unique genres• Extend sections incrementally to avoid redundant work🎯 Result: Sum of all squared diversity scores across all possible shelf sections
Understanding the Visualization
1
Choose Starting Shelf
Pick a starting position in the library shelf
2
Extend Section
Gradually include more books while tracking unique genres
3
Calculate Diversity Score
Square the number of unique genres to emphasize diversity
4
Repeat for All Sections
Do this for every possible shelf section and sum all scores
Key Takeaway
🎯 Key Insight: By fixing the starting position and extending subarrays incrementally while maintaining a hash set, we efficiently calculate distinct counts without redundant work, achieving optimal O(n²) time complexity for this subarray enumeration problem.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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