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
🎨 Art Gallery: Complete Exhibition Finder🎭 1πŸŽͺ 3🎭 1🎨 2🎨 2Gallery Collection: 3 Art Types (🎭Drama, πŸŽͺCircus, 🎨Painting)Complete Exhibition RoomContains all 3 art types! ✨Left Boundary (Expandable)Right Boundary🎯 Found complete room? Count all possible extensions to the right!Sliding window efficiently finds and counts without redundant checksSlide & Count Pattern
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)!
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
24.7K Views
Medium Frequency
~18 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