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 Squares121index 0index 1index 2All Subarrays and Their Distinct Counts[1] → distinct elements: {1} → count = 1 → 1² = 1[1,2] → distinct elements: {1,2} → count = 2 → 2² = 4[1,2,1] → distinct elements: {1,2} → count = 2 → 2² = 4[2] → distinct elements: {2} → count = 1 → 1² = 1[2,1] → distinct elements: {1,2} → count = 2 → 2² = 4[1] → distinct elements: {1} → count = 1 → 1² = 1Final Answer: 1 + 4 + 4 + 1 + 4 + 1 = 15
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
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