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 Sum INPUT Array: arr 1 i=0 3 i=1 5 i=2 All Subarrays: [1] sum=1 (odd) [3] sum=3 (odd) [5] sum=5 (odd) [1,3] sum=4 (even) [3,5] sum=8 (even) [1,3,5] sum=9 (odd) arr = [1, 3, 5] ALGORITHM STEPS 1 Initialize Counters oddCount=0, evenCount=1 2 Track Running Sum prefixSum = 0, result = 0 3 For Each Element Update prefix sum parity 4 Count Logic If odd: add evenCount If even: add oddCount Running Trace: i val sum parity result - - 0 even 0 0 1 1 odd 1 1 3 4 even 2 2 5 9 odd 4 FINAL RESULT Subarrays with Odd Sum: [1] --> sum = 1 [3] --> sum = 3 [5] --> sum = 5 [1,3,5] --> sum = 9 Total Count: 4 Output: 4 Key Insight: odd - odd = even and even - even = even. If current prefix sum is odd, we need even prefix sums before it to get odd subarray sum. Track count of odd/even prefix sums as we iterate. Time: O(n), Space: O(1). Result modulo 10^9 + 7. TutorialsPoint - Number of Sub-arrays With Odd Sum | Optimized - Running Sum Approach
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