Skip to content

Commit fecbb3d

Browse files
committed
Sync LeetCode submission Runtime - 199 ms (14.24%), Memory - 34.4 MB (45.31%)
1 parent da6d039 commit fecbb3d

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of <strong>good</strong> subarrays of</em> <code>nums</code>.</p>
2+
3+
<p>A subarray <code>arr</code> is <strong>good</strong> if there are <strong>at least </strong><code>k</code> pairs of indices <code>(i, j)</code> such that <code>i &lt; j</code> and <code>arr[i] == arr[j]</code>.</p>
4+
5+
<p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> nums = [1,1,1,1,1], k = 10
12+
<strong>Output:</strong> 1
13+
<strong>Explanation:</strong> The only good subarray is the array nums itself.
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> nums = [3,1,4,3,2,2,4], k = 2
20+
<strong>Output:</strong> 4
21+
<strong>Explanation:</strong> There are 4 different good subarrays:
22+
- [3,1,4,3,2,2] that has 2 pairs.
23+
- [3,1,4,3,2,2,4] that has 3 pairs.
24+
- [1,4,3,2,2,4] that has 2 pairs.
25+
- [4,3,2,2,4] that has 2 pairs.
26+
</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
33+
<li><code>1 &lt;= nums[i], k &lt;= 10<sup>9</sup></code></li>
34+
</ul>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Approach 1: Two pointers
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
from collections import Counter
7+
8+
class Solution:
9+
def countGood(self, nums: List[int], k: int) -> int:
10+
n = len(nums)
11+
same, right = 0, -1
12+
count = Counter()
13+
ans = 0
14+
15+
for left in range(n):
16+
while same < k and right + 1 < n:
17+
right += 1
18+
same += count[nums[right]]
19+
count[nums[right]] += 1
20+
if same >= k:
21+
ans += n - right
22+
count[nums[left]] -= 1
23+
same -= count[nums[left]]
24+
25+
return ans

0 commit comments

Comments
 (0)