Skip to main content
  1. LeetCode/

LeetCode 2799: Count Complete Subarrays in an Array

·1 min· ·
LeetCode Daily Medium
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-04-21

  • Total time: 15:00.00

Intuition
#

The length of this problem is quite small,
so we can use brute-force to iterate through two arrays and count the subarrays.
However, there is an optimized method:
while iterating from the start index to the end index,
once the current subarray already satisfies the complete condition,
we can immediately stop iterating further and directly count the number of satisfied subarrays from the current end index to the end of the array.
This optimization helps to avoid TLE (Time Limit Exceeded) issues.

Approach
#

class Solution:
    def countCompleteSubarrays(self, nums):
        distinct_elements = set(nums)
        total_distinct = len(distinct_elements)
        count = 0
        n = len(nums)
        
        for i in range(n):
            current_set = set()
            for j in range(i, n):
                current_set.add(nums[j])
                if len(current_set) == total_distinct:
                    count += (n - j)
                    break
        return count

Findings
#

NA

Encountered Problems
#

NA

Related

LeetCode 2145: Count the Hidden Sequences
·2 mins
LeetCode Daily Medium
LeetCode Problem Solving
LeetCode 781: Rabbits in Forest
·2 mins
LeetCode Daily Medium
LeetCode Problem Solving
LeetCode 560: Subarray Sum Equals K
·2 mins
LeetCode Daily Medium Prefix Sum
LeetCode Problem Solving
LeetCode 1922: Count Good Numbers
·2 mins
LeetCode Daily Medium
LeetCode Problem Solving
LeetCode 2381: Shifting Letters II
·2 mins
LeetCode Medium Difference Array
LeetCode Problem Solving
LeetCode 3522: Calculate Score After Performing Instructions
·1 min
LeetCode Weekly Medium
LeetCode Problem Solving