Advertisement
Home Data Structure Arrays Count Subarrays with Odd Sum

Count Subarrays with Odd Sum

0
Advertisement

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

  1. Let prefix[i] be the sum of the first i elements, with prefix[0] = 0 for the empty prefix.
  2. The subarray from index j to i - 1 has sum prefix[i] - prefix[j], which is odd exactly when the two prefixes have different parities.
  3. Keep two counters, evenPrefixes and oddPrefixes, for the prefixes seen so far. Start with evenPrefixes = 1 because the empty prefix is even.
  4. For each element, flip the running parity if the element is odd.
  5. If the current parity is odd, every earlier even prefix forms an odd subarray, so add evenPrefixes to the answer. Otherwise add oddPrefixes.
  6. Record the current prefix by incrementing the counter that matches its parity, then move on.
  7. Return the answer as a long, since the count can reach about n² / 2.

Java Program

Java
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

  • evenPrefixes and oddPrefixes count how many prefix sums of each parity have been seen, including the empty prefix.
  • num & 1 extracts the lowest bit of num. 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 expression num % 2 would return -1 for negative odd numbers.
  • Adding that bit to parity and masking with & 1 flips 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.

Iterationnumparity (after)count (before)addedcount (after)even / odd (after)
12even0oddPrefixes = 002 / 0
23odd0evenPrefixes = 222 / 1
34odd2evenPrefixes = 242 / 2
45even4oddPrefixes = 263 / 2
56even6oddPrefixes = 284 / 2
67odd8evenPrefixes = 4124 / 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

Java
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

Java
int[] nums = {2, 4, 6};
System.out.println(countOddSumSubarrays(nums));
// Output: 0
// Every sum of even numbers is even

Example 3: Negative Numbers

Java
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 = 0 makes [1, 3, 5] return 2 instead of 4, because subarrays that start at index 0 are never counted. Initialize evenPrefixes = 1.
  • Using an int counter – an array of 100,000 odd numbers has about 2.5 billion odd subarrays, which overflows int and gives a negative result. Declare count as long.
  • Testing oddness with num % 2 == 1 – this misses negative odd numbers such as -3, since -3 % 2 is -1. Use (num & 1) == 1 or num % 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 count first, 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.

Java
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 count after 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.