Skip to content

Commit 7158168

Browse files
committed
292. Number of Sub-arrays With Odd Sum
1 parent d70dc8f commit 7158168

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Given an array of integers arr, return the number of subarrays with an odd sum.
2+
3+
# Since the answer can be very large, return it modulo 109 + 7.
4+
5+
6+
7+
# Example 1:
8+
9+
# Input: arr = [1,3,5]
10+
# Output: 4
11+
# Explanation: 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+
# Example 2:
15+
16+
# Input: arr = [2,4,6]
17+
# Output: 0
18+
# Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
19+
# All sub-arrays sum are [2,6,12,4,10,6].
20+
# All sub-arrays have even sum and the answer is 0.
21+
# Example 3:
22+
23+
# Input: arr = [1,2,3,4,5,6,7]
24+
# Output: 16
25+
26+
27+
# Constraints:
28+
29+
# 1 <= arr.length <= 105
30+
# 1 <= arr[i] <= 100
31+
32+
from typing import List
33+
34+
class Solution:
35+
def numOfSubarrays(self, arr: List[int]) -> int:
36+
n = len(arr)
37+
odd_count = 0
38+
prefix_sum = 0
39+
mod = 10**9+7
40+
41+
for el in arr:
42+
prefix_sum += el
43+
odd_count += prefix_sum % 2
44+
45+
odd_count += (n - odd_count) * odd_count
46+
47+
return odd_count % mod
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
from solution import Solution
3+
4+
5+
class TestSolution(unittest.TestCase):
6+
7+
def test_case_1(self):
8+
sol = Solution()
9+
self.assertEqual(sol.numOfSubarrays([1,3,5]), 4)
10+
11+
def test_case_2(self):
12+
sol = Solution()
13+
self.assertEqual(sol.numOfSubarrays([2,4,6]), 0)
14+
15+
def test_case_3(self):
16+
sol = Solution()
17+
self.assertEqual(sol.numOfSubarrays([1,2,3,4,5,6,7]), 16)

0 commit comments

Comments
 (0)