The Wayback Machine - https://web.archive.org/web/20240710135441/https://www.geeksforgeeks.org/number-of-subarrays-having-even-product/
Open In App

Number of subarrays having even product

Last Updated : 04 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers, the task is to count the total number of subarrays having even product.

Examples :

Input: arr[] = { 7, 5, 4, 9 }
Output: 6
Explanation: There are total 6 subarrays

  1. { 4 }
  2. { 5, 4 }
  3. { 7, 5, 4 }
  4. { 7, 5, 4, 9 }
  5. { 5, 4, 9 }
  6. { 4, 9 }

Input: arr[] = { 1, 3, 5 }
Output: 0

Naive Approach: The simplest approach to solve this problem is to generate all possible subarrays from the given array and for each subarray, check if its product is even or not. If found to be true for any subarray, increase count. Finally, print the count obtained.

Below is the implementation of the above approach:
 

C++




// CPP implementation of the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to count subarrays with even product
void evenproduct(int arr[], int length)
{
   
  // Stores count of subarrays
  // with even product
  int count = 0;
 
  // Traverse the array
  for (int i = 0; i < length+1; i++) {
 
    // Initialize product
    int product = 1;
 
    for (int j = i; j < length+1; j++) {
 
      // Update product of the subarray
      product *= arr[j];
 
      if (product % 2 == 0)
        ++count;
    }
  }
 
  // Print total count of subarrays
  cout<<count;
}
 
// Driver Code
int main()
{
   
  // Input
  int arr[] = { 7, 5, 4, 9 };
 
  // Length of an array
  int length = (sizeof(arr)/sizeof(arr[0]))- 1;
 
  // Function call to count
  // subarrays with even product
  evenproduct(arr, length);
}
 
// This code is contributed by ipg2016107


Java




// Java implementation of the above approach
import java.io.*;
 
class GFG {
 
    // Function to count subarrays with even product
    static void evenproduct(int arr[], int length)
    {
        // Stores count of subarrays
        // with even product
        int count = 0;
 
        // Traverse the array
        for (int i = 0; i < arr.length; i++) {
 
            // Initialize product
            int product = 1;
 
            for (int j = i; j < arr.length; j++) {
 
                // Update product of the subarray
                product *= arr[j];
 
                if (product % 2 == 0)
                    ++count;
            }
        }
 
        // Print total count of subarrays
        System.out.println(count);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Input
        int arr[] = { 7, 5, 4, 9 };
 
        // Length of an array
        int length = arr.length - 1;
 
        // Function call to count
        // subarrays with even product
        evenproduct(arr, length);
    }
}


Python3




# Python3 implementation of the above approach
 
# Function to count subarrays with even product
def evenproduct(arr, length) :
   
  # Stores count of subarrays
  # with even product
  count = 0;
 
  # Traverse the array
  for i in range(length + 1) :
 
    # Initialize product
    product = 1;
    for j in range(i, length + 1) :
 
      # Update product of the subarray
      product *= arr[j];
 
      if (product % 2 == 0) :
          count += 1;
 
  # Print total count of subarrays
  print(count);
 
# Driver Code
if __name__ == "__main__" :
   
    # Input
    arr = [ 7, 5, 4, 9 ];
     
    # Length of an array
    length = len(arr) - 1;
     
    # Function call to count
    # subarrays with even product
    evenproduct(arr, length);
 
    # This code is contributed by AnkThon


C#




// C# implementation of the above approach
using System;
public class GFG
{
 
  // Function to count subarrays with even product
  static void evenproduct(int []arr, int length)
  {
 
    // Stores count of subarrays
    // with even product
    int count = 0;
 
    // Traverse the array
    for (int i = 0; i < arr.Length; i++) {
 
      // Initialize product
      int product = 1;
 
      for (int j = i; j < arr.Length; j++) {
 
        // Update product of the subarray
        product *= arr[j];
 
        if (product % 2 == 0)
          ++count;
      }
    }
 
    // Print total count of subarrays
    Console.WriteLine(count);
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
     
    // Input
    int []arr = { 7, 5, 4, 9 };
 
    // Length of an array
    int length = arr.Length - 1;
 
    // Function call to count
    // subarrays with even product
    evenproduct(arr, length);
  }
}
 
// This code is contributed by AnkThon


Javascript




<script>
 
// Javascript implementation of the above approach
 
// Function to count subarrays with even product
function evenproduct(arr, length)
{
   
  // Stores count of subarrays
  // with even product
  var count = 0;
  var i,j;
  // Traverse the array
  for (i = 0; i < length+1; i++) {
 
    // Initialize product
    var product = 1;
 
    for (j = i; j < length+1; j++) {
 
      // Update product of the subarray
      product *= arr[j];
 
      if (product % 2 == 0)
        ++count;
    }
  }
 
  // Print total count of subarrays
  document.write(count);
}
 
// Driver Code
   
  // Input
  var arr = [7, 5, 4, 9];
 
  // Length of an array
  var length = arr.length;
 
  // Function call to count
  // subarrays with even product
  evenproduct(arr, length);
 
</script>


 
 

Output: 

6

 

Time Complexity: O(N2)
Auxiliary Space: O(1) 

Efficient Approach: Follow the steps below to optimize the above approach:

  1. The total number of subarrays in an array of size N is N * (N + 1) / 2.
  2. The count of subarrays with an odd product is equal to the total number of continuous odd elements present in the array.
  3. Therefore, count of subarrays with even product = (Total number of subarrays – Subarrays with the odd product).
  4. Print the obtained value of the count of subarrays.

Below is the implementation of the above approach:

 

C++




#include <iostream>
using namespace std;
 
// Function to count subarrays
// with even product
void evenproduct(int arr[],
                 int length)
{
   
  // Total number of subarrays
  int total_subarray
    = length * (length + 1) / 2;
 
  // Counter variables
  int total_odd = 0;
  int count_odd = 0;
 
  // Traverse the array
  for (int i = 0; i < length; ++i) {
 
    // If current element is odd
    if (arr[i] % 2 == 0) {
      count_odd = 0;
    }
    else {
 
      ++count_odd;
 
      // Update count of subarrays
      // with odd product up to index i
      total_odd += count_odd;
    }
  }
 
  // Print count of subarrays
  // with even product
  cout << (total_subarray
           - total_odd) << endl;
}
 
// Driver code
int main()
{
 
  // Input
  int arr[] = { 7, 5, 4, 9 };
 
  // Length of an array
  int length = sizeof(arr) / sizeof(arr[0]);
 
  // Function call to count
  // even product subarrays
  evenproduct(arr, length);
 
  return 0;
}
 
// This code is contributed by splevel62.


Java




// Java implementation of the above approach
import java.io.*;
 
class GFG {
 
    // Function to count subarrays
    // with even product
    static void evenproduct(int arr[],
                            int length)
    {
        // Total number of subarrays
        int total_subarray
            = length * (length + 1) / 2;
 
        // Counter variables
        int total_odd = 0;
        int count_odd = 0;
 
        // Traverse the array
        for (int i = 0; i < arr.length; ++i) {
 
            // If current element is odd
            if (arr[i] % 2 == 0) {
                count_odd = 0;
            }
            else {
 
                ++count_odd;
 
                // Update count of subarrays
                // with odd product up to index i
                total_odd += count_odd;
            }
        }
 
        // Print count of subarrays
        // with even product
        System.out.println(total_subarray
                           - total_odd);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Input
        int arr[] = { 7, 5, 4, 9 };
 
        // Length of an array
        int length = arr.length;
 
        // Function call to count
        // even product subarrays
        evenproduct(arr, length);
    }
}


Python3




# Function to count subarrays
# with even product
def evenproduct(arr, length):
 
    # Total number of subarrays
    total_subarray = length * (length + 1) // 2
 
    # Counter variables
    total_odd = 0
    count_odd = 0
 
    # Traverse the array
    for i in range(length):
 
        # If current element is odd
        if (arr[i] % 2 == 0):
            count_odd = 0
 
        else:
            count_odd += 1
 
            # Update count of subarrays
            # with odd product up to index i
            total_odd += count_odd
 
    # Print count of subarrays
    # with even product
    print(total_subarray
          - total_odd)
 
# Driver code
if __name__ == "__main__":
 
    # Input
    arr = [7, 5, 4, 9]
 
    # Length of an array
    length = len(arr)
 
    # Function call to count
    # even product subarrays
    evenproduct(arr, length)
 
    # This code is contributed by ukasp.


C#




// C# program for the above approach
using System;
class GFG
{
 
  // Function to count subarrays
  // with even product
  static void evenproduct(int[] arr,
                          int length)
  {
 
    // Total number of subarrays
    int total_subarray
      = length * (length + 1) / 2;
 
    // Counter variables
    int total_odd = 0;
    int count_odd = 0;
 
    // Traverse the array
    for (int i = 0; i < arr.Length; ++i) {
 
      // If current element is odd
      if (arr[i] % 2 == 0) {
        count_odd = 0;
      }
      else {
 
        ++count_odd;
 
        // Update count of subarrays
        // with odd product up to index i
        total_odd += count_odd;
      }
    }
 
    // Print count of subarrays
    // with even product
    Console.WriteLine(total_subarray
                      - total_odd);
  }
 
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    // Input
    int[] arr = { 7, 5, 4, 9 };
 
    // Length of an array
    int length = arr.Length;
 
    // Function call to count
    // even product subarrays
    evenproduct(arr, length);
  }
}
 
// This code is contributed by code_hunt.


Javascript




<script>
 
// javascript implementation of the above approach
 
   // Function to count subarrays
    // with even product
    function evenproduct(arr, length)
    {
        // Total number of subarrays
        var total_subarray
            = length * (length + 1) / 2;
 
        // Counter variables
        var total_odd = 0;
        var count_odd = 0;
 
        // Traverse the array
        for (i = 0; i < arr.length; ++i) {
 
            // If current element is odd
            if (arr[i] % 2 == 0) {
                count_odd = 0;
            }
            else {
 
                ++count_odd;
 
                // Update count of subarrays
                // with odd product up to index i
                total_odd += count_odd;
            }
        }
 
        // Print count of subarrays
        // with even product
        document.write(total_subarray
                           - total_odd);
    }
 
    // Driver Code
 // Input
    var arr = [ 7, 5, 4, 9 ];
 
    // Length of an array
    var length = arr.length;
 
    // Function call to count
    // even product subarrays
    evenproduct(arr, length);
// This code is contributed by Amit Katiyar
</script>


 
 

Output: 

6

 

Time Complexity: O(N)
Auxiliary Space: O(1) 



Similar Reads

Count subarrays having product equal to the power of a given Prime Number
Given an array arr[] of size N and an integer M, the task is to count the number of subarrays having product of its elements equal to the power of M, where M is a prime number. Examples: Input: arr[] = {2, 2, 2, 2}, M = 2Output: 10Explanation: All possible non-empty subarrays having product equal to the power of M = (4 * (4 + 1)) / 2 = 10 Input: ar
8 min read
Number of subarrays having product less than K
Given an array of positive numbers, calculate the number of possible contiguous subarrays having product lesser than a given number K. Examples : Input : arr[] = [1, 2, 3, 4] K = 10Output : 7The subarrays are {1}, {2}, {3}, {4}, {1, 2}, {1, 2, 3} and {2, 3} Input : arr[] = [1, 9, 2, 8, 6, 4, 3] K = 100Output : 16 Input : arr[] = [10, 5, 2, 6] K = 1
13 min read
Split an Array to maximize subarrays having equal count of odd and even elements for a cost not exceeding K
Given an array arr[] of size N and an integer K, the task is to split the given array into maximum possible subarrays having equal count of even and odd elements such that the cost to split the array does not exceed K. The cost to split an array into a subarray is the difference between the last and first elements of the subarrays respectively. Exa
8 min read
Count of subarrays of size K with elements having even frequencies
Given an array arr[] and an integer K, the task is to count subarrays of size K in which every element appears an even number of times in the subarray. Examples: Input: arr[] = {1, 4, 2, 10, 2, 10, 0, 20}, K = 4 Output: 1 Explanation: Only subarray {2, 10, 2, 10} satisfies the required condition. Input: arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20}, K = 3
9 min read
Count subarrays having sum of elements at even and odd positions equal
Given an array arr[] of integers, the task is to find the total count of subarrays such that the sum of elements at even position and sum of elements at the odd positions are equal. Examples: Input: arr[] = {1, 2, 3, 4, 1}Output: 1Explanation: {3, 4, 1} is the only subarray in which sum of elements at even position {3, 1} = sum of element at odd po
7 min read
Count even length subarrays having bitwise XOR equal to 0
Given an array arr[] of size N, the task is to count all possible even length subarrays having bitwise XOR of subarray elements equal to 0. Examples: Input: arr[] = {2, 2, 3, 3, 6, 7, 8}Output: 3Explanation:Subarrays having XOR of elements equal to 0 are: {{2, 2}, {3, 3}, {2, 2, 3, 3}}Therefore, the required output is 3. Input: arr[] = {1, 2, 3, 3}
13 min read
Count subarrays having even Bitwise OR
Given an array arr[] consisting of N positive integers, the task is to count the number of subarrays whose Bitwise OR of its elements even. Examples: Input: arr[] = {1, 5, 4, 2, 6 }Output: 6Explanation:The subarrays with even Bitwise OR are {4}, {2}, {6}, {2, 6}, {4, 2}, {4, 2, 6}.Therefore, the number of subarrays having even Bitwise OR are 6. Inp
7 min read
Count subarrays having even Bitwise XOR
Given an array arr[] of size N, the task is to count the number of subarrays from the given array whose Bitwise XOR is even. Examples: Input: arr[] = {1, 2, 3, 4}Output: 4Explanation: The subarrays having even Bitwise XOR are {{2}, {4}, {1, 2, 3}, {1, 2, 3, 4}}. Input: arr[] = {2, 4, 6}Output: 6Explanation: The subarrays having even Bitwise XOR are
11 min read
Find all possible subarrays having product less than or equal to K
Given an array arr[], the task is to print all possible subarrays having a product of its elements less than or equal to K. Input: arr[] = {2, 1, 3, 4, 5, 6, 2}, K = 10 Output: [[2], [1], [2, 1], [3], [1, 3], [2, 1, 3], [4], [5], [6], [2]] Explanation: All possible subarrays having product ? K are {2}, {1}, {2, 1}, {3}, {1, 3}, {2, 1, 3}, {4}, {5},
13 min read
Count of subarrays having product as a perfect cube
Given an array arr[] consisting of N positive integers, the task is to count the number of subarrays with product of its elements equal to a perfect cube. Examples: Input: arr[] = {1, 8, 4, 2}Output: 6Explanation:The subarrays with product of elements equal to a perfect cube are: {1}. Therefore, product of subarray = 1 (= (1)3).{1, 8}. Therefore, p
14 min read
three90RightbarBannerImg