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 of nums consisting of all the indices from i to j such that 0 <= i <= j < nums.length.
  • Then the number of distinct values in nums[i..j] is called the distinct count of nums[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
Subarrays Distinct Element Sum of Squares INPUT nums array: 1 i=0 2 i=1 1 i=2 All Subarrays: [1] distinct=1 [2] distinct=1 [1] distinct=1 [1,2] distinct=2 [2,1] distinct=2 [1,2,1] distinct=2 Distinct Counts: [1, 1, 1, 2, 2, 2] 6 subarrays total ALGORITHM STEPS 1 Extend Subarrays Start at each index i 2 Track Distinct Elements Use set for each subarray 3 Square Each Count Calculate count^2 4 Sum All Squares Accumulate total Calculation Process: Subarray Distinct Square [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 FINAL RESULT Sum of Squared Distinct Counts 15 OK Breakdown: 1^2 = 1 1^2 = 1 1^2 = 1 2^2 = 4 2^2 = 4 2^2 = 4 Key Insight: The "Extend Subarrays" approach iterates through each starting index i, then extends to each ending index j. For each extension, we track distinct elements incrementally using a set/hash. This avoids recounting from scratch. Time: O(n^2), Space: O(n). Square each distinct count and sum all values. TutorialsPoint - Subarrays Distinct Element Sum of Squares I | Optimized - Extend Subarrays
Asked in
Google 15 Microsoft 12
8.5K Views
Medium Frequency
~15 min Avg. Time
234 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