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
🎯 Light Switch Analogy for [1, 3, 5]OFFPrefix: 0Count: 1+1 (odd)ONPrefix: 1Count: 1+1 to result+3 (odd)OFFPrefix: 4Count: 2+1 to result+5 (odd)ONPrefix: 9Count: 2+2 to resultWhy This Works:β€’ Odd numbers flip the switch (change parity)β€’ Even numbers don't change the switch stateβ€’ Subarray sum is odd ↔ endpoints have different statesβ€’ Count pairs: OFFβ†’ON, ONβ†’OFFFinal Result: 4Total subarrays with odd sum
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!
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 25
62.4K Views
Medium-High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen