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
Count Complete Subarrays: [1,3,1,2,2]13122Total distinct elements: {1, 2, 3} = 3Complete subarrays (have exactly 3 distinct):[1,3,1,2], [1,3,1,2,2], [3,1,2], [3,1,2,2]Total Complete Subarrays: 4Goal: Count all subarrays matching total distinct count
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
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 18
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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