Title: Count Subarrays with Odd Sum
In this guide, you’ll learn how to count the subarrays of an integer array whose sum is odd. It is a popular interview question because the obvious solution is slow, while a small observation about parity makes it run in a single pass.
Let’s explore the brute-force idea first, then replace it with a prefix-parity approach that needs only O(n) time and O(1) extra space.
Understanding the Problem
Given an array nums, a subarray is a contiguous, non-empty slice of it. We want the number of subarrays whose elements add up to an odd number.
For [1, 3, 5] there are six subarrays. Only [1], [3], [5] and [1, 3, 5] have odd sums, so the answer is 4.
Checking every subarray works, but it costs O(n²) time. The key insight is that the sum of a subarray is the difference of two prefix sums, and the parity of a difference depends only on the parities of the two prefix sums.
Approach / Algorithm Steps
- Let
prefix[i]be the sum of the firstielements, withprefix[0] = 0for the empty prefix. - The subarray from index
jtoi - 1has sumprefix[i] - prefix[j], which is odd exactly when the two prefixes have different parities. - Keep two counters,
evenPrefixesandoddPrefixes, for the prefixes seen so far. Start withevenPrefixes = 1because the empty prefix is even. - For each element, flip the running
parityif the element is odd. - If the current parity is odd, every earlier even prefix forms an odd subarray, so add
evenPrefixesto the answer. Otherwise addoddPrefixes. - Record the current prefix by incrementing the counter that matches its parity, then move on.
- Return the answer as a
long, since the count can reach about n² / 2.
Java Program
public class CountSubarraysWithOddSum {
public static long countOddSumSubarrays(int[] nums) {
if (nums == null) {
throw new IllegalArgumentException("Array must not be null");
}
long evenPrefixes = 1; // the empty prefix has sum 0, which is even
long oddPrefixes = 0;
int parity = 0; // parity of the running prefix sum
long count = 0;
for (int num : nums) {
parity = (parity + (num & 1)) & 1;
if (parity == 1) {
count += evenPrefixes;
oddPrefixes++;
} else {
count += oddPrefixes;
evenPrefixes++;
}
}
return count;
}
public static void main(String[] args) {
int[] nums = {1, 3, 5};
System.out.println("Odd-sum subarrays: " + countOddSumSubarrays(nums));
}
}Explanation of the Program
evenPrefixesandoddPrefixescount how many prefix sums of each parity have been seen, including the empty prefix.num & 1extracts the lowest bit ofnum. It is 1 for odd numbers and 0 for even numbers, and it also works for negative values because Java uses two’s complement. The expressionnum % 2would return -1 for negative odd numbers.- Adding that bit to
parityand masking with& 1flips the parity only when the element is odd, so we never store the full prefix sum and cannot overflow. - When the new prefix is odd, it pairs with each earlier even prefix to form an odd subarray, and the reverse holds when it is even.
- The counter update happens after the addition, so a prefix is never paired with itself.
Step-by-Step Trace
Let’s trace [2, 3, 4, 5, 6, 7], where the expected answer is 12. Before the loop, evenPrefixes = 1, oddPrefixes = 0 and count = 0.
| Iteration | num | parity (after) | count (before) | added | count (after) | even / odd (after) |
|---|---|---|---|---|---|---|
| 1 | 2 | even | 0 | oddPrefixes = 0 | 0 | 2 / 0 |
| 2 | 3 | odd | 0 | evenPrefixes = 2 | 2 | 2 / 1 |
| 3 | 4 | odd | 2 | evenPrefixes = 2 | 4 | 2 / 2 |
| 4 | 5 | even | 4 | oddPrefixes = 2 | 6 | 3 / 2 |
| 5 | 6 | even | 6 | oddPrefixes = 2 | 8 | 4 / 2 |
| 6 | 7 | odd | 8 | evenPrefixes = 4 | 12 | 4 / 3 |
At the end of each iteration, count holds the number of odd-sum subarrays that end at or before the current index.
Examples
Example 1: Mixed Odd Elements
int[] nums = {1, 3, 5};
System.out.println(countOddSumSubarrays(nums));
// Output: 4
// Odd sums: [1], [3], [5], [1, 3, 5]Example 2: All Even Elements
int[] nums = {2, 4, 6};
System.out.println(countOddSumSubarrays(nums));
// Output: 0
// Every sum of even numbers is evenExample 3: Negative Numbers
int[] nums = {-1, 2, -3};
System.out.println(countOddSumSubarrays(nums));
// Output: 4
// Odd sums: [-1], [-3], [-1, 2], [2, -3]Common Mistakes to Avoid
These are the slips that most often break this solution.
- Forgetting the empty prefix – starting with
evenPrefixes = 0makes[1, 3, 5]return 2 instead of 4, because subarrays that start at index 0 are never counted. InitializeevenPrefixes = 1. - Using an int counter – an array of 100,000 odd numbers has about 2.5 billion odd subarrays, which overflows
intand gives a negative result. Declarecountaslong. - Testing oddness with num % 2 == 1 – this misses negative odd numbers such as -3, since
-3 % 2is -1. Use(num & 1) == 1ornum % 2 != 0. - Updating counters before counting – incrementing the matching counter first pairs the current prefix with itself and overcounts by one per element. Add to
countfirst, then increment. - Adding the matching parity – an odd prefix paired with an odd prefix gives an even difference. Add the opposite parity counter.
Edge Cases to Test
Run through these inputs before calling the solution finished.
- Single odd element
- Single even element
- All even elements
- All odd elements
- Negative odd elements
- Large values near Integer.MAX_VALUE
- Empty array
- Null array reference
Additional Considerations
The loop visits each element once, so the time complexity is O(n). The program stores only four scalars, so the space complexity is O(1).
Tracking parity instead of the real prefix sum matters for large values. Summing numbers near Integer.MAX_VALUE would overflow an int prefix, but a single parity bit cannot overflow. An empty array returns 0 naturally, while a null array is rejected explicitly.
For comparison, here is the brute-force version. It is easy to verify but runs in O(n²), so it is useful mainly as a test oracle.
public static long bruteForce(int[] nums) {
long count = 0;
for (int i = 0; i < nums.length; i++) {
long sum = 0;
for (int j = i; j < nums.length; j++) {
sum += nums[j];
if ((sum & 1) == 1) {
count++;
}
}
}
return count;
}Interview Follow-up Questions
Interviewers often extend the problem in these directions.
- What if you need the number of even-sum subarrays instead? – the total is n * (n + 1) / 2, so subtract the odd count, or pair equal-parity prefixes directly.
- What if the answer must be returned modulo 1,000,000,007? – apply the modulo to
countafter each addition; the counters themselves stay small enough to remain exact. - What if the numbers arrive as a stream of unknown length? – the algorithm already keeps only two counters and a parity bit, so you can process each value as it arrives and report the running answer.
- What if you need subarrays whose sum is divisible by k? – generalize parity to remainders mod k, keep a count array of size k for prefix remainders, and pair equal remainders.
Conclusion
Counting odd-sum subarrays becomes simple once you see that only the parity of each prefix sum matters. Two counters and a parity bit replace the nested loops and bring the cost down from O(n²) to O(n).
Try adapting the program to count even-sum subarrays or sums divisible by k. You can learn more about similar problems in our Java array programs category.



