Number of Sub-arrays With Odd Sum - Problem
Given an array of integers arr, you need to find the number of contiguous subarrays whose sum is odd.
A subarray is a contiguous part of an array. For example, in array [1, 2, 3], the subarrays are: [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3].
Key insight: A sum is odd if it contains an odd number of odd elements. This mathematical property allows us to solve the problem efficiently using dynamic programming or prefix sum techniques.
Since the answer can be very large, return it modulo 109 + 7.
Input & Output
example_1.py β Basic case
$
Input:
arr = [1, 3, 5]
βΊ
Output:
4
π‘ Note:
The subarrays with odd sum are: [1] (sum=1), [3] (sum=3), [5] (sum=5), and [1,3] (sum=4 is even, so this is wrong). Actually: [1] (sum=1), [3] (sum=3), [5] (sum=5), [1,3,5] (sum=9). Wait, let me recalculate: [1]=1β, [3]=3β, [5]=5β, [1,3]=4β, [3,5]=8β, [1,3,5]=9β. So 4 is correct.
example_2.py β Mixed even/odd
$
Input:
arr = [2, 4, 6]
βΊ
Output:
0
π‘ Note:
All elements are even, so any subarray sum will be even. No subarrays have odd sum.
example_3.py β Single element
$
Input:
arr = [1]
βΊ
Output:
1
π‘ Note:
Only one subarray [1] with sum 1, which is odd.
Constraints
- 1 β€ arr.length β€ 105
- 1 β€ arr[i] β€ 109
- Return result modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Switch State
Start with switch OFF (even prefix sum = 0), even_count = 1
2
Process Each Number
Add number to running sum, check if switch state changed
3
Count Valid Pairs
Current state can pair with all previous opposite states
4
Update State Counter
Increment counter for current switch state
Key Takeaway
π― Key Insight: Each element either flips the parity switch or keeps it the same. Count valid ONβOFF transitions to find all subarrays with odd sums in O(n) time!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code