Skip to content

Commit c70b6f9

Browse files
committed
Sync LeetCode submission Runtime - 87 ms (69.32%), Memory - 24.7 MB (12.98%)
1 parent e57781c commit c70b6f9

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>. A continuous subarray is called <strong>nice</strong> if there are <code>k</code> odd numbers on it.</p>
2+
3+
<p>Return <em>the number of <strong>nice</strong> sub-arrays</em>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [1,1,2,1,1], k = 3
10+
<strong>Output:</strong> 2
11+
<strong>Explanation:</strong> The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> nums = [2,4,6], k = 1
18+
<strong>Output:</strong> 0
19+
<strong>Explanation:</strong> There are no odd numbers in the array.
20+
</pre>
21+
22+
<p><strong class="example">Example 3:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> nums = [2,2,2,1,2,2,1,2,2,2], k = 2
26+
<strong>Output:</strong> 16
27+
</pre>
28+
29+
<p>&nbsp;</p>
30+
<p><strong>Constraints:</strong></p>
31+
32+
<ul>
33+
<li><code>1 &lt;= nums.length &lt;= 50000</code></li>
34+
<li><code>1 &lt;= nums[i] &lt;= 10^5</code></li>
35+
<li><code>1 &lt;= k &lt;= nums.length</code></li>
36+
</ul>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Approach 1: Hashing
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
8+
curr_sum = 0
9+
subarrays = 0
10+
prefix_sum = {curr_sum : 1}
11+
12+
for num in nums:
13+
curr_sum += num % 2
14+
if curr_sum - k in prefix_sum:
15+
subarrays += prefix_sum[curr_sum - k]
16+
prefix_sum[curr_sum] = prefix_sum.get(curr_sum, 0) + 1
17+
18+
return subarrays
19+

0 commit comments

Comments
 (0)