Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

A complete subarray contains every distinct value present anywhere in the array. For a fixed start, once an end position has collected all those values, extending farther cannot lose completeness, so all later endpoints can be counted at once.

Approach

Count the array's distinct values. For each starting index, create an empty set and extend the endpoint, inserting encountered values. At the first endpoint whose set reaches the required size, add n - endpoint and stop scanning that start. Return the total. These reference solutions use independent nested scans rather than a sliding window; the early break only avoids recounting already-known complete extensions.

class Solution: def countCompleteSubarrays(self, nums: List[int]) -> int: n = len(nums) target = len(set(nums)) res = 0 for i in range(n): seen = set() for j in range(i, n): seen.add(nums[j]) if len(seen) == target: res += n - j break return res

Complexity analysis

Let n = nums.length and u be the total number of distinct values. Time: O(n^2) in the worst case for the nested start/end enumeration. Auxiliary space: O(u) for the per-start set.