Are you looking for a step-by-step explanation of Leetcode's "2799. Count Complete Subarrays in an Array"? You’re at the right place! In this blog, we’ll go from a basic brute force solution to a highly efficient sliding window approach, and explain each concept in a simple way.
Problem Statement (Leetcode 2799)
You are given an array of positive integers. A subarray is a contiguous part of the array (meaning elements must be next to each other).
We define a "complete" subarray as one that contains all distinct elements that are present in the entire array.
Example 1:
Explanation:
The distinct elements in the whole array are {1, 2, 3}
.
The subarrays that contain all of them are:
-
[1, 3, 1, 2]
-
[1, 3, 1, 2, 2]
-
[3, 1, 2]
-
[3, 1, 2, 2]
Total = 4 complete subarrays ✅
What is the goal of this problem ?
Approach 1: Brute Force (Try All Subarrays)
Let’s start with the most basic idea. What if we try every possible subarray and check if it contains all the distinct elements?
👨🏫 Steps:
-
Count the number of distinct elements in the full array.
-
Try all subarrays using two loops.
-
For each subarray, use a map to count its unique elements.
-
If the number of unique elements equals the total, it's a complete subarray.
🧾 C++ Code:
⚡ Drawback of Brute Force:
🚀 Approach 2: Sliding Window (Optimized)
- Instead of checking all subarrays, we’ll use a window that moves through the array and tracks how many distinct elements are inside.
- When our window has all the required distinct elements, every subarray starting from that point to the end of the window is valid.
👨🏫 Steps:
- Use a set to count the total number of unique elements.
- Use two pointers i and j to mark the sliding window.
- Use a map to track how many times each number appears in the current window.
- When the current window has all distinct elements:
- Every subarray from i to j is valid → add (n - j) to answer.
- Then move i forward to try smaller windows.
🧾 C++ Code:
🧒 Easy Real-Life Analogy
- Always understand the problem deeply before optimizing.
- Learn to spot patterns like “number of distinct elements” → good candidate for sliding window.
- Practice both approaches for stronger coding interviews!