Count Complete Subarrays in an Array
Master this topic with zero to advance depth.
Count Complete Subarrays in an Array
A subarray is complete if the number of distinct elements in it is equal to the number of distinct elements in the entire array.
Visual Representation
nums = [1, 3, 1, 2, 2], Total Distinct: 3
[1, 3, 1, 2] (Distinct: 3, VALID!)
[3, 1, 2] (Distinct: 3, VALID!)
[1, 2, 2] (Distinct: 2, INVALID)Examples
Input: nums = [1,3,1,2,2]
Output: 4
Approach 1
Level I: Brute Force
Intuition
Find the total number of distinct elements in the array first. Then, check every subarray and count how many are complete.
⏱ O(N^2)💾 O(N)
Approach 2
Level III: Optimal (Sliding Window)
Intuition
Thought Process
This is equivalent to finding subarrays with at least k distinct elements. We can use the 'at least' pattern or the 'total - (at most k-1)' pattern.
Calculation
Total Subarrays - Subarrays with at most (K-1) distinct elements.
⏱ O(N)💾 O(N)
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.