Intuition
A subarray has an odd sum exactly when its two bounding prefix sums have different parities, so count how many earlier prefixes of the opposite parity each position sees.
Explanation
Key idea
The sum of the subarray arr[i..j] equals prefix[j+1] - prefix[i], where prefix[k] is the sum of the first k elements (and prefix[0] = 0). That difference is odd exactly when the two prefix sums have different parity: one odd and one even.
So instead of summing every subarray, we scan left to right, keep the running prefix sum's parity, and ask: how many earlier prefixes had the opposite parity? Each such earlier prefix marks the start of an odd-sum subarray ending here. We never need the sums themselves, only whether each prefix is odd or even, so we keep two counters.
Walk-through on arr = [1,3,5]
Start with the empty prefix (sum 0, even), so even = 1, odd = 0, answer = 0.
- Add
1: running sum is odd. Earlier even prefixes =1, so1new odd-sum subarray ends here →answer = 1. Record this odd prefix:odd = 1. - Add
3: running sum is now even (odd + odd). Earlier odd prefixes =1, so1more →answer = 2. Record:even = 2. - Add
5: running sum is odd again. Earlier even prefixes =2, so2more →answer = 4. Record:odd = 2.
Final answer 4, matching the subarrays [1], [1,3,5], [3], [5].
Why it works
Fixing the right end j, every odd-sum subarray arr[i..j] corresponds one-to-one with a starting prefix prefix[i] whose parity differs from prefix[j+1]. Counting those opposite-parity prefixes for every j and summing gives every odd-sum subarray exactly once.
Since the count can be huge, take it modulo 10^9 + 7 as you go.
Complexity
- Time: O(n). One pass, O(1) work per element.
- Space: O(1). Two parity counters.
Implementation
class Solution {
public int numOfSubarrays(int[] arr) {
final int MOD = 1_000_000_007;
long even = 1, odd = 0; // empty prefix has sum 0, which is even
int parity = 0;
long ans = 0;
for (int num : arr) {
parity ^= num & 1;
// Odd-sum subarrays ending here start at an opposite-parity prefix.
ans += (parity == 1) ? even : odd;
if (parity == 1) odd++;
else even++;
ans %= MOD;
}
return (int) ans;
}
}