Count Complete Subarrays in an Array - Problem
You are given an array nums consisting of positive integers.
We call a subarray of an array complete if the following condition is satisfied:
- The number of distinct elements in the subarray is equal to the number of distinct elements in the whole array.
Return the number of complete subarrays.
A subarray is a contiguous non-empty part of an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,3,1,2,2]
›
Output:
4
💡 Note:
Complete subarrays are [1,3,1,2], [1,3,1,2,2], [3,1,2], [3,1,2,2]. All have 3 distinct elements like the whole array {1,2,3}.
Example 2 — All Same Elements
$
Input:
nums = [2,2,2,2,2]
›
Output:
15
💡 Note:
Only 1 distinct element (2) in whole array. All 15 possible subarrays have exactly 1 distinct element, so all are complete.
Example 3 — All Different Elements
$
Input:
nums = [5,5,5,5]
›
Output:
10
💡 Note:
Only 1 distinct element (5). All subarrays: [5], [5], [5], [5], [5,5], [5,5], [5,5], [5,5,5], [5,5,5], [5,5,5,5] = 10 total subarrays.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 2000
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Array [1,3,1,2,2] has 3 distinct elements: {1,2,3}
2
Find Complete
Search subarrays with exactly 3 distinct elements
3
Count Result
Found 4 complete subarrays total
Key Takeaway
🎯 Key Insight: Once a subarray contains all distinct elements, extending it right keeps it complete
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code