Number of Sub-arrays With Odd Sum Problem
Description
LeetCode Problem 1524.
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 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Constraints:
1 <= arr.length <= 10^51 <= arr[i] <= 100
Solution
Approach: Prefix Sum Parity
Let prefix[i] be the sum of the first i elements, with prefix[0] = 0. The subarray arr[j..i-1] has sum prefix[i] - prefix[j], and that is odd exactly when the two prefix sums have different parities.
So the number of odd subarrays ending at a position is the number of earlier prefixes (including the empty one) whose parity is the opposite of the current prefix. Scan the array keeping:
parity: the parity of the current prefix sum,count[0],count[1]: how many prefixes seen so far are even / odd. Start withcount = [1, 0]for the empty prefix, which is even.
For each element, update parity, add count[1 - parity] to the answer, then count the current prefix with count[parity]++.
The answer can be about n2 / 4 (2.5 · 109 for n = 105), so take it modulo 10^9 + 7 as you go.
Complexity: O(n) time and O(1) extra space.
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
mod = 10**9 + 7
count = [1, 0] # prefixes seen so far with an even / odd sum (the empty prefix is even)
ans = parity = 0
for x in arr:
parity ^= x & 1
# a subarray ending here is odd when it starts after a prefix of the other parity
ans = (ans + count[parity ^ 1]) % mod
count[parity] += 1
return ans