Skip to content

Commit b56f88e

Browse files
committed
Sync LeetCode submission Runtime - 28 ms (70.47%), Memory - 21.5 MB (5.54%)
1 parent c70b6f9 commit b56f88e

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<p>Given a binary array <code>nums</code> and an integer <code>goal</code>, return <em>the number of non-empty <strong>subarrays</strong> with a sum</em> <code>goal</code>.</p>
2+
3+
<p>A <strong>subarray</strong> is a contiguous part of the array.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [1,0,1,0,1], goal = 2
10+
<strong>Output:</strong> 4
11+
<strong>Explanation:</strong> The 4 subarrays are bolded and underlined below:
12+
[<u><strong>1,0,1</strong></u>,0,1]
13+
[<u><strong>1,0,1,0</strong></u>,1]
14+
[1,<u><strong>0,1,0,1</strong></u>]
15+
[1,0,<u><strong>1,0,1</strong></u>]
16+
</pre>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> nums = [0,0,0,0,0], goal = 0
22+
<strong>Output:</strong> 15
23+
</pre>
24+
25+
<p>&nbsp;</p>
26+
<p><strong>Constraints:</strong></p>
27+
28+
<ul>
29+
<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>
30+
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
31+
<li><code>0 &lt;= goal &lt;= nums.length</code></li>
32+
</ul>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Approach 1: Prefix Sum
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
8+
total_count = 0
9+
curr_sum = 0
10+
sum_freq = {0 : 1} # {prefix_sum : frequency}
11+
12+
for num in nums:
13+
curr_sum += num
14+
if curr_sum - goal in sum_freq:
15+
total_count += sum_freq[curr_sum - goal]
16+
17+
sum_freq[curr_sum] = sum_freq.get(curr_sum, 0) + 1
18+
19+
return total_count
20+
21+
22+

0 commit comments

Comments
 (0)