Subarrays Distinct Element Sum of Squares I - Problem
You are given a 0-indexed integer array nums.
The distinct count of a subarray of nums is defined as:
- Let
nums[i..j]be a subarray ofnumsconsisting of all the indices fromitojsuch that0 <= i <= j < nums.length. - Then the number of distinct values in
nums[i..j]is called the distinct count ofnums[i..j].
Return the sum of the squares of distinct counts of all subarrays of nums.
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:
Subarrays: [1]→1²=1, [1,2]→2²=4, [1,2,1]→2²=4, [2]→1²=1, [2,1]→2²=4, [1]→1²=1. Sum = 1+4+4+1+4+1 = 15
Example 2 — All Same Elements
$
Input:
nums = [1,1,1]
›
Output:
6
💡 Note:
All subarrays have distinct count 1: [1]→1, [1,1]→1, [1,1,1]→1, [1]→1, [1,1]→1, [1]→1. Sum = 6×1² = 6
Example 3 — All Different Elements
$
Input:
nums = [1,2]
›
Output:
6
💡 Note:
Subarrays: [1]→1²=1, [1,2]→2²=4, [2]→1²=1. Sum = 1+4+1 = 6
Constraints
- 1 ≤ nums.length ≤ 100
- 1 ≤ nums[i] ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array [1,2,1]
2
Find Subarrays
Generate all contiguous subarrays and count distinct elements
3
Sum Squares
Square each distinct count and sum all results
Key Takeaway
🎯 Key Insight: Generate all subarrays, count distinct elements using a set, square each count, and sum the results
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code