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
Understanding the Visualization
1
Input Array
Given array with possible duplicate elements
2
Generate Subarrays
Find all contiguous subarrays and count distinct elements
3
Square and Sum
Square each distinct count and sum all results
Key Takeaway
🎯 Key Insight: Count distinct elements efficiently in all subarrays and sum their squares
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code