#1524
Number of Sub-arrays With Odd Sum
MediumArrayMathDynamic ProgrammingPrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
We can use prefix sums to track the count of even and odd sums as we iterate through the array. This allows us to efficiently count subarrays with odd sums without explicitly calculating each subarray's sum.
⚙️
Algorithm
5 steps- 1Step 1: Initialize counters for odd and even prefix sums.
- 2Step 2: Iterate through the array and maintain a running sum.
- 3Step 3: For each element, check if the running sum is odd or even.
- 4Step 4: If the sum is odd, add the count of even prefix sums to the result (as they can form odd-sum subarrays). If the sum is even, add the count of odd prefix sums.
- 5Step 5: Update the respective count of odd/even prefix sums.
solution.py16 lines
1# Full working Python code
2
3def numOfSubarrays(arr):
4 odd_count = 0
5 even_count = 1 # We start with one even prefix sum (0)
6 current_sum = 0
7 result = 0
8 for num in arr:
9 current_sum += num
10 if current_sum % 2 != 0:
11 result += even_count
12 odd_count += 1
13 else:
14 result += odd_count
15 even_count += 1
16 return result % (10**9 + 7)ℹ
Complexity note: The complexity is O(n) because we only make a single pass through the array, maintaining a constant amount of additional space.
- 1Subarrays with odd sums can be efficiently counted using prefix sums.
- 2The relationship between odd and even sums allows us to use counts instead of explicit sums.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.