Subarrays Distinct Element Sum of Squares I - Problem
Subarray Analysis: You are given a
For each subarray
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
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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code