Count subarrays with same even and odd elements

Given an array of N integers, count number of even-odd subarrays. An even – odd subarray is a subarray that contains the same number of even as well as odd integers.

Examples :

Input : arr[] = {2, 5, 7, 8} 
Output : 3
Explanation : There are total 3 even-odd subarrays.
               1) {2, 5}
               2) {7, 8}
               3) {2, 5, 7, 8}

Input : arr[] = {3, 4, 6, 8, 1, 10} 
Output : 3
Explanation : In this case, 3 even-odd subarrays are:
               1) {3, 4}
               2) {8, 1}
               3) {1, 10}

This problem is mainly a variation of count subarrays with equal number of 0s and 1s.



A naive approach would be to check for all possible subarrays using two loops, whether they are even-odd subarrays or not. This approach will take O(N^2) time.

An Efficient approach solves the problem in O(N) time and it is based on following ideas:

  • Even-odd subarrays will always be of even length.
  • Maintaining track of the difference between the frequency of even and odd integers.
  • Hashing of this difference of frequencies is useful in finding number of even-odd subarrays.

The basic idea is to use the difference between the frequency of odd and even numbers to obtain an optimal solution. We will maintain two integer hash arrays for the positive and negative value of the difference.
-> Example to understand in better way :
-> Consider difference = freq(odd) – freq(even)
-> To calculate this difference, increment the value of ‘difference’ when there is
an odd integer and decrement it when there is an even integer. (initially, difference = 0)
arr[] = {3, 4, 6, 8, 1, 10}

index 0 1 2 3 4 5 6

array 3 4 6 8 1 10

difference 0 1 0 -1 -2 -1 -2

-> Observe that whenever a value ‘k’ repeats in the ‘difference’ array, there exists an
even-odd subarray for each previous occurrence of that value i.e. subarray exists from
index i + 1 to j where difference[i] = k and difference[j] = k.

-> Value ‘0’ is repeated in ‘difference’ array at index 2 and hence subarray exists for
(0, 2] indexes. Similarly, for repetition of values ‘-1’ (at indexes 3 and 5) and ‘-2’ (at
indexes 4 and 6), subarray exists for (3, 5] and (4, 6] indexes.

Below is the implementation of the O(N) solution described above.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

/*C++ program to find total number of
even-odd subarrays present in given array*/
#include <iostream>
using namespace std;
  
// function that returns the count of subarrays that
// contain equal number of odd as well as even numbers
int countSubarrays(int arr[], int n)
{
    // initialize difference and answer with 0
    int difference = 0;
    int ans = 0;
  
    // create two auxiliary hash arrays to count frequency
    // of difference, one array for non-negative difference 
    // and other array for negative difference. Size of these
    // two auxiliary arrays is 'n+1' because difference can
    // reach maximum value 'n' as well as minimum value '-n'
    int hash_positive[n + 1], hash_negative[n + 1];
  
    // initialize these auxiliary arrays with 0
    fill_n(hash_positive, n + 1, 0);
    fill_n(hash_negative, n + 1, 0);
  
    // since the difference is initially 0, we have to 
    // initialize hash_positive[0] with 1
    hash_positive[0] = 1;
  
    // for loop to iterate through whole 
    // array (zero-based indexing is used)
    for (int i = 0; i < n ; i++)
    {
        // incrementing or decrementing difference based on 
        // arr[i] being even or odd, check if arr[i] is odd 
        if (arr[i] & 1 == 1)
            difference++;
        else
            difference--;
  
        // adding hash value of 'difference' to our answer
        // as all the previous occurrences of the same
        // difference value will make even-odd subarray
        // ending at index 'i'. After that, we will increment
        // hash array for that 'difference' value for
        // its occurrence at index 'i'. if difference is 
        // negative then use hash_negative
        if (difference < 0)
        {
            ans += hash_negative[-difference];
            hash_negative[-difference]++;
        }
          
        // else use hash_positive
        else
        {
            ans += hash_positive[difference];
            hash_positive[difference]++;
        }
    }
  
    // return total number of even-odd subarrays
    return ans;
}
  
// Driver code
int main()
{
    int arr[] = {3, 4, 6, 8, 1, 10, 5, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
      
    // Printing total number of even-odd subarrays
    cout << "Total Number of Even-Odd subarrays"
        " are " << countSubarrays(arr,n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

//Java program to find total 
// number of even-odd subarrays 
// present in given array 
class GFG {
  
    // function that returns the 
    // count of subarrays that 
    // contain equal number of 
    // odd as well as even numbers 
    static int countSubarrays(int[] arr,
            int n) {
        // initialize difference 
        // and answer with 0 
        int difference = 0;
        int ans = 0;
  
        // create two auxiliary hash 
        // arrays to count frequency 
        // of difference, one array 
        // for non-negative difference 
        // and other array for negative 
        // difference. Size of these 
        // two auxiliary arrays is 'n+1' 
        // because difference can 
        // reach maximum value 'n' as 
        // well as minimum value '-n' 
        // initialize these 
        // auxiliary arrays with 0 
        int[] hash_positive = new int[n + 1];
        int[] hash_negative = new int[n + 1];
  
        // since the difference is 
        // initially 0, we have to 
        // initialize hash_positive[0] with 1 
        hash_positive[0] = 1;
  
        // for loop to iterate 
        // through whole array 
        // (zero-based indexing is used) 
        for (int i = 0; i < n; i++) {
            // incrementing or decrementing 
            // difference based on 
            // arr[i] being even or odd, 
            // check if arr[i] is odd 
            if ((arr[i] & 1) == 1) {
                difference++;
            } else {
                difference--;
            }
  
            // adding hash value of 'difference' 
            // to our answer as all the previous 
            // occurrences of the same difference 
            // value will make even-odd subarray 
            // ending at index 'i'. After that, 
            // we will increment hash array for 
            // that 'difference' value for its 
            // occurrence at index 'i'. if 
            // difference is negative then use 
            // hash_negative 
            if (difference < 0) {
                ans += hash_negative[-difference];
                hash_negative[-difference]++;
            } // else use hash_positive 
            else {
                ans += hash_positive[difference];
                hash_positive[difference]++;
            }
        }
  
        // return total number 
        // of even-odd subarrays 
        return ans;
    }
  
    // Driver code 
    public static void main(String[] args) {
        int[] arr = new int[]{3, 4, 6, 8,
            1, 10, 5, 7};
        int n = arr.length;
  
        // Printing total number 
        // of even-odd subarrays 
        System.out.println("Total Number of Even-Odd"
                + " subarrays are "
                + countSubarrays(arr, n));
    }
  
  
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find total
# number of even-odd subarrays
# present in given array
  
# function that returns the count 
# of subarrays that contain equal
# number of odd as well as even numbers 
def countSubarrays(arr, n): 
  
    # initialize difference and 
    # answer with 0 
    difference = 0
    ans = 0
  
    # create two auxiliary hash 
    # arrays to count frequency 
    # of difference, one array 
    # for non-negative difference 
    # and other array for negative 
    # difference. Size of these two 
    # auxiliary arrays is 'n+1' 
    # because difference can reach 
    # maximum value 'n' as well as
    # minimum value '-n' 
    hash_positive = [0] * (n + 1)
    hash_negative = [0] * (n + 1)
  
    # since the difference is 
    # initially 0, we have to 
    # initialize hash_positive[0] with 1 
    hash_positive[0] = 1
  
    # for loop to iterate through 
    # whole array (zero-based 
    # indexing is used) 
    for i in range(n): 
      
        # incrementing or decrementing 
        # difference based on arr[i]
        # being even or odd, check if
        # arr[i] is odd 
        if (arr[i] & 1 == 1): 
            difference = difference + 1
        else:
            difference = difference - 1
  
        # adding hash value of 'difference' 
        # to our answer as all the previous
        # occurrences of the same difference 
        # value will make even-odd subarray 
        # ending at index 'i'. After that, 
        # we will increment hash array for 
        # that 'difference' value for 
        # its occurrence at index 'i'. if 
        # difference is negative then use
        # hash_negative 
        if (difference < 0): 
            ans += hash_negative[-difference]
            hash_negative[-difference] = hash_negative[-difference] + 1
          
        # else use hash_positive 
        else:
            ans += hash_positive[difference]
            hash_positive[difference] = hash_positive[difference] + 1
  
    # return total number of 
    # even-odd subarrays 
    return ans 
  
# Driver code 
arr = [3, 4, 6, 8, 1, 10, 5, 7
n = len(arr) 
  
# Printing total number
# of even-odd subarrays 
print("Total Number of Even-Odd subarrays are " +
                    str(countSubarrays(arr, n))) 
  
# This code is contributed
# by Yatin Gupta

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find total 
// number of even-odd subarrays
// present in given array
using System;
  
class GFG
{
    // function that returns the
    // count of subarrays that
    // contain equal number of 
    // odd as well as even numbers
    static int countSubarrays(int []arr, 
                              int n)
    {
        // initialize difference 
        // and answer with 0
        int difference = 0;
        int ans = 0;
      
        // create two auxiliary hash 
        // arrays to count frequency
        // of difference, one array
        // for non-negative difference 
        // and other array for negative
        // difference. Size of these
        // two auxiliary arrays is 'n+1'
        // because difference can
        // reach maximum value 'n' as 
        // well as minimum value '-n'
        int []hash_positive = new int[n + 1];
        int []hash_negative = new int[n + 1];
      
        // initialize these 
        // auxiliary arrays with 0
        Array.Clear(hash_positive, 0, n + 1);
        Array.Clear(hash_negative, 0, n + 1);
      
        // since the difference is
        // initially 0, we have to 
        // initialize hash_positive[0] with 1
        hash_positive[0] = 1;
      
        // for loop to iterate 
        // through whole array 
        // (zero-based indexing is used)
        for (int i = 0; i < n ; i++)
        {
            // incrementing or decrementing 
            // difference based on 
            // arr[i] being even or odd, 
            // check if arr[i] is odd 
            if ((arr[i] & 1) == 1)
                difference++;
            else
                difference--;
      
            // adding hash value of 'difference' 
            // to our answer as all the previous 
            // occurrences of the same difference
            // value will make even-odd subarray
            // ending at index 'i'. After that, 
            // we will increment hash array for 
            // that 'difference' value for its 
            // occurrence at index 'i'. if 
            // difference is negative then use 
            // hash_negative
            if (difference < 0)
            {
                ans += hash_negative[-difference];
                hash_negative[-difference]++;
            }
              
            // else use hash_positive
            else
            {
                ans += hash_positive[difference];
                hash_positive[difference]++;
            }
        }
      
        // return total number 
        // of even-odd subarrays
        return ans;
    }
      
    // Driver code
    static void Main()
    {
        int []arr = new int[]{3, 4, 6, 8, 
                              1, 10, 5, 7};
        int n = arr.Length;
          
        // Printing total number 
        // of even-odd subarrays
        Console.Write("Total Number of Even-Odd" +
                               " subarrays are "
                           countSubarrays(arr,n));
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to find total number of
// even-odd subarrays present in given array
  
// function that returns the count of subarrays 
// that contain equal number of odd as well 
// as even numbers
function countSubarrays(&$arr, $n)
{
    // initialize difference and 
    // answer with 0
    $difference = 0;
    $ans = 0;
  
    // create two auxiliary hash arrays to count 
    // frequency of difference, one array for 
    // non-negative difference and other array 
    // for negative difference. Size of these
    // two auxiliary arrays is 'n+1' because 
    // difference can reach maximum value 'n'
    // as well as minimum value '-n'
    $hash_positive = array_fill(0, $n + 1, NULL);
    $hash_negative = array_fill(0, $n + 1, NULL);
  
    // since the difference is initially 0, we 
    // have to initialize hash_positive[0] with 1
    $hash_positive[0] = 1;
  
    // for loop to iterate through whole 
    // array (zero-based indexing is used)
    for ($i = 0; $i < $n ; $i++)
    {
        // incrementing or decrementing difference 
        // based on arr[i] being even or odd, check 
        // if arr[i] is odd 
        if ($arr[$i] & 1 == 1)
            $difference++;
        else
            $difference--;
  
        // adding hash value of 'difference' to our 
        // answer as all the previous occurrences of 
        // the same difference value will make even-odd 
        // subarray ending at index 'i'. After that, we 
        // will increment hash array for that 'difference' 
        // value for its occurrence at index 'i'. if 
        // difference is negative then use hash_negative
        if ($difference < 0)
        {
            $ans += $hash_negative[-$difference];
            $hash_negative[-$difference]++;
        }
          
        // else use hash_positive
        else
        {
            $ans += $hash_positive[$difference];
            $hash_positive[$difference]++;
        }
    }
  
    // return total number of even-odd 
    // subarrays
    return $ans;
}
  
// Driver code
$arr = array(3, 4, 6, 8, 1, 10, 5, 7);
$n = sizeof($arr);
  
// Printing total number of even-odd 
// subarrays
echo "Total Number of Even-Odd subarrays".
     " are " . countSubarrays($arr, $n);
  
// This code is contributed by ita_c
?>

chevron_right


Output:

Total Number of Even-Odd subarrays are 7

Time Complexity : O(N), where N is the number of integers.
Auxiliary Space : O(2N), where N is the number of integers.



My Personal Notes arrow_drop_up

A competitive coder developer and a learner by choice who is always eager to contribute to the computer science and developer community

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.