Count Complete Subarrays in an Array — LeetCode 2799 Python Solution

MediumArrayHash TableSliding Window
Problem
#2799
Reading time
2 min

The 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.

Example

Input
nums = [1,3,1,2,2]
Output
4
Explanation
The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].

Python solution

Python
class Solution:
    def countCompleteSubarrays(self, nums: List[int]) -> int:
        cnt = len(set(nums))
        ans, n = 0, len(nums)
        for i in range(n):
            s = set()
            for x in nums[i:]:
                s.add(x)
                if len(s) == cnt:
                    ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2799. Count Complete Subarrays in an Array is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2799. Count Complete Subarrays in an Array?
LeetCode 2799. Count Complete Subarrays in an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2799. Count Complete Subarrays in an Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2799. Count Complete Subarrays in an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2799. Count Complete Subarrays in an Array cover?
LeetCode 2799. Count Complete Subarrays in an Array is tagged Array, Hash Table and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview