Number of Sub-arrays With Odd Sum — LeetCode 1524 Python Solution

MediumArrayMathDynamic ProgrammingPrefix Sum
Problem
#1524
Pattern
Prefix Sum
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview