Skip to content

Commit 469aa6f

Browse files
committed
Sync LeetCode submission Runtime - 87 ms (38.71%), Memory - 21.9 MB (66.67%)
1 parent 5afa8f2 commit 469aa6f

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<p>Given an array of integers <code>arr</code>, return <em>the number of subarrays with an <strong>odd</strong> sum</em>.</p>
2+
3+
<p>Since the answer can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> arr = [1,3,5]
10+
<strong>Output:</strong> 4
11+
<strong>Explanation:</strong> All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
12+
All sub-arrays sum are [1,4,9,3,8,5].
13+
Odd sums are [1,9,3,5] so the answer is 4.
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> arr = [2,4,6]
20+
<strong>Output:</strong> 0
21+
<strong>Explanation:</strong> All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
22+
All sub-arrays sum are [2,6,12,4,10,6].
23+
All sub-arrays have even sum and the answer is 0.
24+
</pre>
25+
26+
<p><strong class="example">Example 3:</strong></p>
27+
28+
<pre>
29+
<strong>Input:</strong> arr = [1,2,3,4,5,6,7]
30+
<strong>Output:</strong> 16
31+
</pre>
32+
33+
<p>&nbsp;</p>
34+
<p><strong>Constraints:</strong></p>
35+
36+
<ul>
37+
<li><code>1 &lt;= arr.length &lt;= 10<sup>5</sup></code></li>
38+
<li><code>1 &lt;= arr[i] &lt;= 100</code></li>
39+
</ul>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Approach 3: Prefix Sum with Odd-Even Counting
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def numOfSubarrays(self, arr: List[int]) -> int:
8+
MOD = 10**9 + 7
9+
count = prefix_sum = 0
10+
11+
odd_count = 0
12+
even_count = 1 # even_count starts as 1 since the initial sum (0) is even
13+
14+
for num in arr:
15+
prefix_sum += num
16+
# If current prefix sum is even, add the number of odd subarrays
17+
if prefix_sum % 2 == 0:
18+
count += odd_count
19+
even_count += 1
20+
21+
# If current prefix sum is odd, add the number of even subarrays
22+
else:
23+
count += even_count
24+
odd_count += 1
25+
26+
count %= MOD
27+
28+
return count
29+
30+

0 commit comments

Comments
 (0)