Number of Sub-arrays With Odd Sum - Problem

Given an array of integers arr, return the number of subarrays with an odd sum.

A subarray is a contiguous part of an array. Since the answer can be very large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,3,5]
Output: 4
💡 Note: All odd-sum subarrays: [1] (sum=1), [3] (sum=3), [5] (sum=5), and [1,3,5] (sum=9). Total count = 4.
Example 2 — Mixed Numbers
$ 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 — Single Element
$ Input: arr = [1]
Output: 1
💡 Note: Only one subarray [1] with sum=1 (odd). Count = 1.

Constraints

  • 1 ≤ arr.length ≤ 105
  • 0 ≤ arr[i] ≤ 109

Visualization

Tap to expand
Number of Sub-arrays With Odd SumInput: [1, 3, 5]135All Subarrays with Odd Sum:[1] = 1 ✓[3] = 3 ✓[5] = 5 ✓[1,3,5] = 9 ✓[1,3] = 4[3,5] = 8Output: 4Count of subarrays with odd sum
Understanding the Visualization
1
Input Array
Given array of integers [1,3,5]
2
Identify Odd Subarrays
Find all contiguous subarrays with odd sum
3
Count Result
Return total count modulo 10^9 + 7
Key Takeaway
🎯 Key Insight: Use prefix sum parity - different parity prefix sums create odd-sum subarrays
Asked in
Google 25 Facebook 20 Amazon 15 Microsoft 12
78.0K Views
Medium Frequency
~25 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