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

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

PythonSolution
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

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

Related problems
No.ProblemDifficulty
1140Stone Game IIMedium
1872Stone Game VIIIHard
2681Power of HeroesHard
0313Super Ugly NumberMedium
0368Largest Divisible SubsetMedium
0396Rotate FunctionMedium

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.

Free to download. Check it runs on your machine, then pick a plan.