Count Complete Subarrays in an Array - Problem
Imagine you have a colorful array of positive integers, and you're on a mission to find all the "complete" subarrays - those special contiguous segments that contain the exact same variety of distinct elements as the entire array!
A subarray is considered complete when:
- It's a contiguous (unbroken) sequence from the original array
- The number of distinct elements in the subarray equals the number of distinct elements in the whole array
Your Goal: Count how many complete subarrays exist in the given array.
Example: If nums = [1,3,1,2,2], the whole array has 3 distinct elements (1, 2, 3). Any subarray with exactly these 3 distinct elements is complete!
Input & Output
example_1.py β Basic Case
$
Input:
nums = [1,3,1,2,2]
βΊ
Output:
4
π‘ Note:
The array has 3 distinct elements: {1,2,3}. Complete subarrays are: [1,3,1,2], [1,3,1,2,2], [3,1,2], [3,1,2,2]. Each contains exactly 3 distinct elements.
example_2.py β All Same Elements
$
Input:
nums = [5,5,5,5]
βΊ
Output:
10
π‘ Note:
Only 1 distinct element (5) exists. Every subarray is complete since they all contain exactly 1 distinct element. Total subarrays = 4+3+2+1 = 10.
example_3.py β All Different Elements
$
Input:
nums = [1,2,3]
βΊ
Output:
1
π‘ Note:
Array has 3 distinct elements. Only the entire array [1,2,3] contains all 3 distinct elements, so there's exactly 1 complete subarray.
Constraints
- 1 β€ nums.length β€ 1000
- 1 β€ nums[i] β€ 1000
- All elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Count Art Types
First, catalog all different types of artwork in your collection
2
Sliding Exhibition
Use a sliding window to find rooms that showcase every art type
3
Count Valid Rooms
Once you have a complete room, count all extensions that remain complete
Key Takeaway
π― Key Insight: Instead of checking every possible subarray individually, we use sliding window to efficiently identify complete regions and count all valid extensions at once, reducing complexity from O(nΒ³) to O(n)!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code