Print number of odd sum sub-arrays of an array

Share

Problem: For a given array of positive or negative integers, find count of sub-arrays whose sum is odd.

Problem Explanation: For a given array a ={1, -2, 3, 4, -5},  odd sum sub-arrays are {1}, {1, -2}, {1, -2 , 3, 4, -5}, {-2, 3}, {-2, 3, 4}, {3}, {3, 4}, {4, -5}, {-5}. Hence, output will be 9.

Java Implementation

public int oddSumSubArrays(int arr[]) {
    int[] count = new int[2]; //count[0] stores count of even sum array, 
                              //count[1] stores count of odd sum array
    int sum = 0;

    for (int i = 0; i<arr.length; i++) {
        sum = (sum + arr[i]) % 2;
        count[Math.abs(sum)]++;
    }

    //Total odd sum arrays = Total odd sub arrays obtained from count 
    //+ number of odd even pairs
    int totalOddSumSubArrayCount =count[1] + (count[1]) * (count[0]);

    return (totalOddSumSubArrayCount); 
} 

TimeComplexity: O(n)

Note: If you find any other better way to approach to this problem or you find any issue/error in above code snippets/approaches – please share it in the comments section below and get a chance to enrol free of cost for an online Live Data Structure and Algorithm course (specially designed for interview preparation for software companies like Amazon, Google, Facebook, FlipKart, SnapDeal, HealthKart…)