Skip to content

Commit e8b0fb9

Browse files
committed
Sync LeetCode submission Runtime - 23 ms (38.46%), Memory - 17.8 MB (94.93%)
1 parent e3b8751 commit e8b0fb9

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
2+
3+
<p>We call a subarray of an array <strong>complete</strong> if the following condition is satisfied:</p>
4+
5+
<ul>
6+
<li>The number of <strong>distinct</strong> elements in the subarray is equal to the number of distinct elements in the whole array.</li>
7+
</ul>
8+
9+
<p>Return <em>the number of <strong>complete</strong> subarrays</em>.</p>
10+
11+
<p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p>
12+
13+
<p>&nbsp;</p>
14+
<p><strong class="example">Example 1:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> nums = [1,3,1,2,2]
18+
<strong>Output:</strong> 4
19+
<strong>Explanation:</strong> The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].
20+
</pre>
21+
22+
<p><strong class="example">Example 2:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> nums = [5,5,5,5]
26+
<strong>Output:</strong> 10
27+
<strong>Explanation:</strong> The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.
28+
</pre>
29+
30+
<p>&nbsp;</p>
31+
<p><strong>Constraints:</strong></p>
32+
33+
<ul>
34+
<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
35+
<li><code>1 &lt;= nums[i] &lt;= 2000</code></li>
36+
</ul>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Approach: Sliding Window
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def countCompleteSubarrays(self, nums: List[int]) -> int:
8+
res = 0
9+
count = {}
10+
n = len(nums)
11+
right = 0
12+
distinct = len(set(nums))
13+
14+
for left in range(n):
15+
if left > 0:
16+
remove = nums[left - 1]
17+
count[remove] -= 1
18+
if count[remove] == 0:
19+
count.pop(remove)
20+
while right < n and len(count) < distinct:
21+
add = nums[right]
22+
count[add] = count.get(add, 0) + 1
23+
right += 1
24+
if len(count) == distinct:
25+
res += n - right + 1
26+
27+
return res
28+
29+

0 commit comments

Comments
 (0)