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 in an Array INPUT nums = [1, 3, 1, 2, 2] 1 i=0 3 i=1 1 i=2 2 i=3 2 i=4 Distinct Elements {1, 2, 3} = 3 elements Goal: Count subarrays with exactly 3 distinct elements ALGORITHM STEPS 1 Count Total Distinct Use Set to find k=3 2 Sliding Window Two pointers: left, right 3 Expand Right Add elements to window 4 Shrink and Count When distinct=k, count+=n-r Complete Subarrays Found: [1,3,1,2] i=0..3 [1,3,1,2,2] i=0..4 [3,1,2] i=1..3 [3,1,2,2] i=1..4 All have {1,2,3} distinct FINAL RESULT Complete Subarrays Count 4 Subarray Breakdown 1 3 1 2 OK 1 3 1 2 2 OK 3 1 2 OK 3 1 2 2 OK Key Insight: Use sliding window with two pointers. When window has k distinct elements, all extensions to the right are also complete subarrays. Count (n - right) for each valid position. Time: O(n), Space: O(k). TutorialsPoint - Count Complete Subarrays in an Array | Optimal Solution
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