LeetCode 2799: Count Complete Subarrays in an Array Solution

Master LeetCode problem 2799 (Count Complete Subarrays in an Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2799. Count Complete Subarrays in an Array

Problem Explanation

Explanation:

To solve this problem, we can iterate over all subarrays and count the number of distinct elements in each subarray. If this count is equal to the number of distinct elements in the whole array, then we have found a complete subarray. We can use a HashSet to keep track of distinct elements.

Algorithm:

  1. Initialize a variable result to store the count of complete subarrays.
  2. Iterate over all subarrays using two nested loops.
  3. In the inner loop, maintain a HashSet to store distinct elements of the subarray.
  4. If the count of distinct elements in the subarray is equal to the count of distinct elements in the whole array, increment result.
  5. Return result as the final count of complete subarrays.

Time Complexity: O(n^2) where n is the number of elements in the array. Space Complexity: O(n) for the HashSet.

:

Solution Code

class Solution {
    public int countCompleteSubarrays(int[] nums) {
        int result = 0;
        int n = nums.length;
        
        for (int i = 0; i < n; i++) {
            Set<Integer> set = new HashSet<>();
            int distinctCount = 0;
            for (int j = i; j < n; j++) {
                if (!set.contains(nums[j])) {
                    set.add(nums[j]);
                    distinctCount++;
                }
                if (distinctCount == set.size()) {
                    result++;
                }
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2799 (Count Complete Subarrays in an Array)?

This page provides optimized solutions for LeetCode problem 2799 (Count Complete Subarrays in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2799 (Count Complete Subarrays in an Array)?

The time complexity for LeetCode 2799 (Count Complete Subarrays in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2799 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2799 in Java, C++, or Python.

Back to LeetCode Solutions