MediumNo. 1524
Number of Sub-arrays With Odd Sum — LeetCode 1524 Python Solution
- Pattern
- Prefix Sum
- Topics
- Array, Math, Dynamic Programming, Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array of integers arr, return the number of subarrays with an odd sum. Since the answer can be very large, return it modulo 109 + 7.
Example
- Input
- arr = [1,3,5]
- Output
- 4
- Explanation
- All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
Python solution
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
mod = 10**9 + 7
cnt = [1, 0]
ans = s = 0
for x in arr:
s += x
ans = (ans + cnt[s & 1 ^ 1]) % mod
cnt[s & 1] += 1
return ansComplexity
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 1524. Number of Sub-arrays With Odd Sum is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1140 | Stone Game II | Medium |
| 1872 | Stone Game VIII | Hard |
| 2681 | Power of Heroes | Hard |
| 0313 | Super Ugly Number | Medium |
| 0368 | Largest Divisible Subset | Medium |
| 0396 | Rotate Function | Medium |
Frequently asked questions
- How hard is LeetCode 1524. Number of Sub-arrays With Odd Sum?
LeetCode 1524. Number of Sub-arrays With Odd Sum is rated Medium on LeetCode.
- What topics does LeetCode 1524. Number of Sub-arrays With Odd Sum cover?
LeetCode 1524. Number of Sub-arrays With Odd Sum is tagged Array, Math, Dynamic Programming and Prefix Sum on LeetCode.