You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/2700-2799/2799.Count Complete Subarrays in an Array/README_EN.md
+51-24Lines changed: 51 additions & 24 deletions
Original file line number
Diff line number
Diff line change
@@ -63,7 +63,15 @@ tags:
63
63
64
64
<!-- solution:start -->
65
65
66
-
### Solution 1
66
+
### Solution 1: Hash Table + Enumeration
67
+
68
+
First, we use a hash table to count the number of distinct elements in the array, denoted as $cnt$.
69
+
70
+
Next, we enumerate the left endpoint index $i$ of the subarray and maintain a set $s$ to store the elements in the subarray. Each time we move the right endpoint index $j$ to the right, we add $nums[j]$ to the set $s$ and check whether the size of the set $s$ equals $cnt$. If it equals $cnt$, it means the current subarray is a complete subarray, and we increment the answer by $1$.
71
+
72
+
After the enumeration ends, we return the answer.
73
+
74
+
Time complexity: $O(n^2)$, Space complexity: $O(n)$, where $n$ is the length of the array.
67
75
68
76
<!-- tabs:start -->
69
77
@@ -178,23 +186,28 @@ function countCompleteSubarrays(nums: number[]): number {
Similar to Solution 1, we can use a hash table to count the number of distinct elements in the array, denoted as $cnt$.
224
+
225
+
Next, we use two pointers to maintain a sliding window, where the right endpoint index is $j$ and the left endpoint index is $i$.
226
+
227
+
Each time we fix the left endpoint index $i$, we move the right endpoint index $j$ to the right. When the number of distinct elements in the sliding window equals $cnt$, it means that all subarrays from the left endpoint index $i$ to the right endpoint index $j$ and beyond are complete subarrays. We then increment the answer by $n - j$, where $n$ is the length of the array. Afterward, we move the left endpoint index $i$ one step to the right and repeat the process.
228
+
229
+
Time complexity: $O(n)$, Space complexity: $O(n)$, where $n$ is the length of the array.
209
230
210
231
<!-- tabs:start -->
211
232
@@ -342,27 +363,33 @@ function countCompleteSubarrays(nums: number[]): number {
0 commit comments