Find number of subarrays with even sum
Last Updated :
11 Jul, 2022
Given an array, find the number of subarrays whose sum is even.
Example :
Input : arr[] = {1, 2, 2, 3, 4, 1}
Output : 9
There are possible subarrays with even
sum. The subarrays are
1) {1, 2, 2, 3} Sum = 8
2) {1, 2, 2, 3, 4} Sum = 12
3) {2} Sum = 2 (At index 1)
4) {2, 2} Sum = 4
5) {2, 2, 3, 4, 1} Sum = 12
6) {2} Sum = 2 (At index 2)
7) {2, 3, 4, 1} Sum = 10
8) {3, 4, 1} Sum = 8
9) {4} Sum = 4
O(n2) time and O(1) space method [Brute Force]
We can simply generate all the possible sub-arrays and find whether the sum of all the elements in them is an even or not. If it is even then we will count that sub-array otherwise neglect it.
Implementation:
C++
/* C++ program to count number of sub-arrays
whose sum is even using brute force
Time Complexity - O(N^2)
Space Complexity - O(1) */
#include<iostream>
using namespace std;
int countEvenSum(int arr[], int n)
{
int result = 0;
// Find sum of all subarrays and increment
// result if sum is even
for (int i=0; i<=n-1; i++)
{
int sum = 0;
for (int j=i; j<=n-1; j++)
{
sum = sum + arr[j];
if (sum % 2 == 0)
result++;
}
}
return (result);
}
// Driver code
int main()
{
int arr[] = {1, 2, 2, 3, 4, 1};
int n = sizeof (arr) / sizeof (arr[0]);
cout << "The Number of Subarrays with even"
" sum is " << countEvenSum (arr, n);
return (0);
}
Java
// Java program to count number
// of sub-arrays whose sum is
// even using brute force
// Time Complexity - O(N^2)
// Space Complexity - O(1)
import java.io.*;
class GFG
{
static int countEvenSum(int arr[],
int n)
{
int result = 0;
// Find sum of all subarrays
// and increment result if
// sum is even
for (int i = 0; i <= n - 1; i++)
{
int sum = 0;
for (int j = i; j <= n - 1; j++)
{
sum = sum + arr[j];
if (sum % 2 == 0)
result++;
}
}
return (result);
}
// Driver code
public static void main (String[] args)
{
int arr[] = {1, 2, 2,
3, 4, 1};
int n = arr.length;
System.out.print("The Number of Subarrays"+
" with even sum is ");
System.out.println(countEvenSum(arr, n));
}
}
// This code is contributed by ajit
Python3
# Python 3 program to count number
# of sub-arrays whose sum is even
# using brute force
# Time Complexity - O(N^2)
# Space Complexity - O(1)
def countEvenSum(arr, n):
result = 0
# Find sum of all subarrays and
# increment result if sum is even
for i in range(0, n, 1):
sum = 0
for j in range(i, n, 1):
sum = sum + arr[j]
if (sum % 2 == 0):
result = result + 1
return (result)
# Driver code
if __name__ == '__main__':
arr = [1, 2, 2, 3, 4, 1]
n = len(arr)
print("The Number of Subarrays" ,
"with even sum is",
countEvenSum (arr, n))
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to count number
// of sub-arrays whose sum is
// even using brute force
// Time Complexity - O(N^2)
// Space Complexity - O(1)
using System;
class GFG
{
static int countEvenSum(int []arr,
int n)
{
int result = 0;
// Find sum of all subarrays
// and increment result if
// sum is even
for (int i = 0; i <= n - 1; i++)
{
int sum = 0;
for (int j = i; j <= n - 1; j++)
{
sum = sum + arr[j];
if (sum % 2 == 0)
result++;
}
}
return (result);
}
// Driver code
static public void Main ()
{
int []arr = {1, 2, 2,
3, 4, 1};
int n = arr.Length;
Console.Write("The Number of Subarrays"+
" with even sum is ");
Console.WriteLine(countEvenSum(arr, n));
}
}
// This code is contributed by m_kit
PHP
<?php
// PHP program to count number
// of sub-arrays whose sum is
// even using brute force
// Time Complexity - O(N^2)
// Space Complexity - O(1)
function countEvenSum($arr, $n)
{
$result = 0;
// Find sum of all subarrays
// and increment result if
// sum is even
for ($i = 0; $i <= $n - 1; $i++)
{
$sum = 0;
for ($j = $i; $j <= $n - 1; $j++)
{
$sum = $sum + $arr[$j];
if ($sum % 2 == 0)
$result++;
}
}
return ($result);
}
// Driver code
$arr = array(1, 2, 2, 3, 4, 1);
$n = sizeof ($arr);
echo "The Number of Subarrays ",
"with even sum is " ,
countEvenSum ($arr, $n);
// This code is contributed by ajit
?>
JavaScript
<script>
// Javascript program to count number
// of sub-arrays whose sum is
// even using brute force
// Time Complexity - O(N^2)
// Space Complexity - O(1)
function countEvenSum(arr,
n)
{
let result = 0;
// Find sum of all subarrays
// and increment result if
// sum is even
for (let i = 0; i <= n - 1; i++)
{
let sum = 0;
for (let j = i; j <= n - 1; j++)
{
sum = sum + arr[j];
if (sum % 2 == 0)
result++;
}
}
return (result);
}
// Driver Code
let arr = [1, 2, 2,
3, 4, 1];
let n = arr.length;
document.write("The Number of Subarrays"+
" with even sum is ");
document.write(countEvenSum(arr, n));
</script>
OutputThe Number of Subarrays with even sum is 9
Time Complexity: O(n2)
Auxiliary Space: O(1)
O(n) Time and O(1) Space Method [Efficient]
If we do compute the cumulative sum array in temp[] of our input array, then we can see that the sub-array starting from i and ending at j, has an even sum if temp[] if (temp[j] - temp[i]) % 2 = 0. So, instead of building a cumulative sum array we build a cumulative sum modulo 2 array, and find how many times 0 and 1 appears in temp[] array using handshake formula. [n * (n-1) /2]
Implementation:
C++
/* C++ program to count number of sub-arrays
with even sum using an efficient algorithm
Time Complexity - O(N)
Space Complexity - O(1)*/
#include<iostream>
using namespace std;
int countEvenSum(int arr[], int n)
{
// A temporary array of size 2. temp[0] is
// going to store count of even subarrays
// and temp[1] count of odd.
// temp[0] is initialized as 1 because there
// a single even element is also counted as
// a subarray
int temp[2] = {1, 0};
// Initialize count. sum is sum of elements
// under modulo 2 and ending with arr[i].
int result = 0, sum = 0;
// i'th iteration computes sum of arr[0..i]
// under modulo 2 and increments even/odd count
// according to sum's value
for (int i=0; i<=n-1; i++)
{
// 2 is added to handle negative numbers
sum = ( (sum + arr[i]) % 2 + 2) % 2;
// Increment even/odd count
temp[sum]++;
}
// Use handshake lemma to count even subarrays
// (Note that an even can be formed by two even
// or two odd)
result = result + (temp[0]*(temp[0]-1)/2);
result = result + (temp[1]*(temp[1]-1)/2);
return (result);
}
// Driver code
int main()
{
int arr[] = {1, 2, 2, 3, 4, 1};
int n = sizeof (arr) / sizeof (arr[0]);
cout << "The Number of Subarrays with even"
" sum is " << countEvenSum (arr, n);
return (0);
}
Java
// Java program to count
// number of sub-arrays
// with even sum using an
// efficient algorithm
// Time Complexity - O(N)
// Space Complexity - O(1)
import java.io.*;
class GFG
{
static int countEvenSum(int arr[],
int n)
{
// A temporary array of size 2.
// temp[0] is going to store
// count of even subarrays
// and temp[1] count of odd.
// temp[0] is initialized as
// 1 because there a single even
// element is also counted as
// a subarray
int temp[] = {1, 0};
// Initialize count. sum is
// sum of elements under modulo
// 2 and ending with arr[i].
int result = 0, sum = 0;
// i'th iteration computes sum
// of arr[0..i] under modulo 2
// and increments even/odd count
// according to sum's value
for (int i = 0; i <= n - 1; i++)
{
// 2 is added to handle
// negative numbers
sum = ((sum + arr[i]) %
2 + 2) % 2;
// Increment even/odd count
temp[sum]++;
}
// Use handshake lemma to
// count even subarrays
// (Note that an even can
// be formed by two even
// or two odd)
result = result + (temp[0] *
(temp[0] - 1) / 2);
result = result + (temp[1] *
(temp[1] - 1) / 2);
return (result);
}
// Driver code
public static void main (String[] args)
{
int arr[] = {1, 2, 2, 3, 4, 1};
int n = arr.length;
System.out.println("The Number of Subarrays"+
" with even sum is " +
countEvenSum (arr, n));
}
}
// This code is contributed by ajit
Python 3
# Python 3 program to count number of sub-arrays
# with even sum using an efficient algorithm
# Time Complexity - O(N)
# Space Complexity - O(1)
def countEvenSum(arr, n):
# A temporary array of size 2. temp[0] is
# going to store count of even subarrays
# and temp[1] count of odd.
# temp[0] is initialized as 1 because there
# a single even element is also counted as
# a subarray
temp = [1, 0]
# Initialize count. sum is sum of elements
# under modulo 2 and ending with arr[i].
result = 0
sum = 0
# i'th iteration computes sum of arr[0..i]
# under modulo 2 and increments even/odd
# count according to sum's value
for i in range( n):
# 2 is added to handle negative numbers
sum = ( (sum + arr[i]) % 2 + 2) % 2
# Increment even/odd count
temp[sum]+= 1
# Use handshake lemma to count even subarrays
# (Note that an even can be formed by two even
# or two odd)
result = result + (temp[0] * (temp[0] - 1) // 2)
result = result + (temp[1] * (temp[1] - 1) // 2)
return (result)
# Driver code
if __name__ == "__main__":
arr = [1, 2, 2, 3, 4, 1]
n = len(arr)
print( "The Number of Subarrays with even"
" sum is" , countEvenSum (arr, n))
# This code is contributed by ita_c
C#
// C# program to count
// number of sub-arrays
// with even sum using an
// efficient algorithm
// Time Complexity - O(N)
// Space Complexity - O(1)
using System;
class GFG
{
static int countEvenSum(int []arr,
int n)
{
// A temporary array of size 2.
// temp[0] is going to store
// count of even subarrays
// and temp[1] count of odd.
// temp[0] is initialized as
// 1 because there a single even
// element is also counted as
// a subarray
int []temp = {1, 0};
// Initialize count. sum is
// sum of elements under modulo
// 2 and ending with arr[i].
int result = 0, sum = 0;
// i'th iteration computes sum
// of arr[0..i] under modulo 2
// and increments even/odd count
// according to sum's value
for (int i = 0; i <= n - 1; i++)
{
// 2 is added to handle
// negative numbers
sum = ((sum + arr[i]) %
2 + 2) % 2;
// Increment even
// or odd count
temp[sum]++;
}
// Use handshake lemma to
// count even subarrays
// (Note that an even can
// be formed by two even
// or two odd)
result = result + (temp[0] *
(temp[0] - 1) / 2);
result = result + (temp[1] *
(temp[1] - 1) / 2);
return (result);
}
// Driver code
static public void Main ()
{
int []arr = {1, 2, 2, 3, 4, 1};
int n = arr.Length;
Console.WriteLine("The Number of Subarrays"+
" with even sum is " +
countEvenSum (arr, n));
}
}
// This code is contributed
// by akt_mit
PHP
<?php
// PHP program to count number
// of sub-arrays with even sum
// using an efficient algorithm
// Time Complexity - O(N)
// Space Complexity - O(1)*/
function countEvenSum($arr, $n)
{
// A temporary array of size 2.
// temp[0] is going to store
// count of even subarrays and
// temp[1] count of odd. temp[0]
// is initialized as 1 because
// there a single even element
// is also counted as a subarray
$temp = array(1, 0);
// Initialize count. sum is
// sum of elements under
// modulo 2 and ending with arr[i].
$result = 0; $sum = 0;
// i'th iteration computes
// sum of arr[0..i] under
// modulo 2 and increments
// even/odd count according
// to sum's value
for ($i = 0; $i <= $n - 1; $i++)
{
// 2 is added to handle
// negative numbers
$sum = (($sum + $arr[$i]) %
2 + 2) % 2;
// Increment even/odd
// count
$temp[$sum]++;
}
// Use handshake lemma to
// count even subarrays
// (Note that an even can
// be formed by two even
// or two odd)
$result = $result + (int)($temp[0] *
($temp[0] - 1) / 2);
$result = $result + (int)($temp[1] *
($temp[1] - 1) / 2);
return ($result);
}
// Driver code
$arr = array (1, 2, 2,
3, 4, 1);
$n = sizeof ($arr);
echo "The Number of Subarrays " .
"with even", " sum is " ,
countEvenSum ($arr, $n);
// This code is contributed by ajit
?>
JavaScript
<script>
// Javascript program to count
// number of sub-arrays
// with even sum using an
// efficient algorithm
// Time Complexity - O(N)
// Space Complexity - O(1)
function countEvenSum(arr,n)
{
// A temporary array of size 2.
// temp[0] is going to store
// count of even subarrays
// and temp[1] count of odd.
// temp[0] is initialized as
// 1 because there a single even
// element is also counted as
// a subarray
let temp = [1, 0];
// Initialize count. sum is
// sum of elements under modulo
// 2 and ending with arr[i].
let result = 0, sum = 0;
// i'th iteration computes sum
// of arr[0..i] under modulo 2
// and increments even/odd count
// according to sum's value
for (let i = 0; i <= n - 1; i++)
{
// 2 is added to handle
// negative numbers
sum = ((sum + arr[i]) %
2 + 2) % 2;
// Increment even/odd count
temp[sum]++;
}
// Use handshake lemma to
// count even subarrays
// (Note that an even can
// be formed by two even
// or two odd)
result = result + (temp[0] *
(temp[0] - 1) / 2);
result = result + (temp[1] *
(temp[1] - 1) / 2);
return (result);
}
// Driver code
let arr=[1, 2, 2, 3, 4, 1];
let n = arr.length;
document.write("The Number of Subarrays"+
" with even sum is " +
countEvenSum (arr, n));
// This code is contributed by rag2127
</script>
OutputThe Number of Subarrays with even sum is 9
Time Complexity: O(n)
Auxiliary Space: O(1)
O(n) Time and O(1) Space Method (bottom-up-approach)
If we start counting from last index and keep track of number of subarrays with even sum so far starting from present index then we can calculate number of subarrays with even sum starting from previous index
Implementation:
C++
/* C++ program to count number of sub-arrays
with even sum using an efficient algorithm
Time Complexity - O(N)
Space Complexity - O(1)*/
#include <iostream>
using namespace std;
long long countEvenSum(int a[], int n)
{
// Result may be large enough not to
// fit in int;
long long res = 0;
// To keep track of subarrays with even sum
// starting from index i;
int s = 0;
for (int i = n - 1; i >= 0; i--)
{
if (a[i] % 2 == 1)
{
/* s is the count of subarrays starting from
* index i+1 whose sum was even*/
/*
If a[i] is odd then all subarrays starting from
index i+1 which was odd becomes even when a[i]
gets added to it.
*/
s = n - i - 1 - s;
}
else
{
/*
If a[i] is even then all subarrays starting from
index i+1 which was even remains even and one
extra a[i] even subarray gets added to it.
*/
s = s + 1;
}
res = res + s;
}
return res;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 2, 3, 4, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "The Number of Subarrays with even"
" sum is "
<< countEvenSum(arr, n);
return 0;
}
// This code is contributed by Aditya Anand
Java
// Java program to count
// number of sub-arrays
// with even sum using an
// efficient algorithm
// Time Complexity - O(N)
// Space Complexity - O(1)
import java.io.*;
class GFG {
public static long countEvenSum(int a[], int n)
{
// result may be large enough not to
// fit in int;
long res = 0;
// to keep track of subarrays with even
// sum starting from index i
int s = 0;
for (int i = n - 1; i >= 0; i--)
{
if (a[i] % 2 == 1)
{
// s is the count of subarrays starting from
// index i+1 whose sum was even
/*if a[i] is odd then all subarrays starting
from index i+1 which was odd becomeseven
when a[i] gets added to it.*/
s = n - i - 1 - s;
}
else
{
/*if a[i] is even then all subarrays
starting from index i+1 which was even remainseven
and one extra a[i] even subarray gets added to it.*/
s = s + 1;
}
res = res + s;
}
return res;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 2, 3, 4, 1 };
int n = arr.length;
System.out.println("The Number of Subarrays"
+ " with even sum is "
+ countEvenSum(arr, n));
}
}
// This code is contributed by Aditya Anand
Python3
# Python 3 program to count number of sub-arrays
# with even sum using an efficient algorithm
# Time Complexity - O(N)
# Space Complexity - O(1)
def countEvenSum(arr, n):
# result may be large
# enough not to fit in int;
res = 0
# to keep track of subarrays
# with even sum starting from index i
s = 0
for i in reversed(range(n)):
if arr[i] % 2 == 1:
# s is the count of subarrays
# starting from index i+1
# whose sum was even
"""
if a[i] is odd then all subarrays
starting from index i+1 which was
odd becomes even when a[i] gets
added to it.
"""
s = n-i-1-s
else:
"""
if a[i] is even then all subarrays
starting from index i+1 which was
even remains even and one extra a[i]
even subarray gets added to it.
"""
s = s+1
res = res + s
return res
# Driver code
if __name__ == "__main__":
arr = [1, 2, 2, 3, 4, 1]
n = len(arr)
print("The Number of Subarrays with even"
" sum is", countEvenSum(arr, n))
# This code is contributed by Aditya Anand
C#
// C# program to count
// number of sub-arrays
// with even sum using an
// efficient algorithm
// Time Complexity - O(N)
// Space Complexity - O(1)
using System;
public class GFG
{
public static long countEvenSum(int[] a, int n)
{
// result may be large enough not to
// fit in int;
long res = 0;
// to keep track of subarrays with even
// sum starting from index i
int s = 0;
for (int i = n - 1; i >= 0; i--)
{
if (a[i] % 2 == 1)
{
// s is the count of subarrays starting from
// index i+1 whose sum was even
/*if a[i] is odd then all subarrays starting
from index i+1 which was odd becomeseven
when a[i] gets added to it.*/
s = n - i - 1 - s;
}
else
{
/*if a[i] is even then all subarrays
starting from index i+1 which was even remainseven
and one extra a[i] even subarray gets added to it.*/
s = s + 1;
}
res = res + s;
}
return res;
}
// Driver Code
static public void Main ()
{
int[] arr = { 1, 2, 2, 3, 4, 1 };
int n = arr.Length;
Console.WriteLine("The Number of Subarrays"
+ " with even sum is "
+ countEvenSum(arr, n));
}
}
// This code is contributed by avanitrachhadiya2155
JavaScript
<script>
// Javascript program to count
// number of sub-arrays
// with even sum using an
// efficient algorithm
// Time Complexity - O(N)
// Space Complexity - O(1)
function countEvenSum(a, n)
{
// result may be large enough not to
// fit in int;
let res = 0;
// to keep track of subarrays with even
// sum starting from index i
let s = 0;
for (let i = n - 1; i >= 0; i--)
{
if (a[i] % 2 == 1)
{
// s is the count of subarrays starting from
// index i+1 whose sum was even
/*if a[i] is odd then all subarrays starting
from index i+1 which was odd becomeseven
when a[i] gets added to it.*/
s = n - i - 1 - s;
}
else
{
/*if a[i] is even then all subarrays
starting from index i+1 which was even remainseven
and one extra a[i] even subarray gets added to it.*/
s = s + 1;
}
res = res + s;
}
return res;
}
let arr = [ 1, 2, 2, 3, 4, 1 ];
let n = arr.length;
document.write("The Number of Subarrays" +
" with even sum is " + countEvenSum(arr, n));
</script>
OutputThe Number of Subarrays with even sum is 9
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Subarrays with k odd numbers Given an integer array arr[] of size n, and an integer k. Your task is to find the number of contiguous subarrays in the array arr[], which contains exactly k odd numbers.Examples : Input : arr = [2, 5, 6, 9], k = 2 Output: 2Explanation: There are 2 subarrays with 2 odds: [2, 5, 6, 9] and [5, 6, 9].
15+ min read
Subarray with Given Sum - Handles Negative Numbers Given an unsorted array of integers, find a subarray that adds to a given number. If there is more than one subarray with the sum of the given number, print any of them.Examples: Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33Output: Sum found between indexes 2 and 4Explanation: Sum of elements betwee
13 min read
Number of subarrays having even product 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: 6Explanation: There are total 6 subarrays { 4 }{ 5, 4 }{ 7, 5, 4 }{ 7, 5, 4, 9 }{ 5, 4, 9 }{ 4, 9 } Input: arr[] = { 1, 3, 5 }Output:
9 min read
Balancing Odd-Even Index Sums with Subarray Negation Given an array A[] of size N. The task is to check whether the sum of elements of A on the odd and even indexes is equal or not, where you are allowed to choose a subarray A[i, j] with 1 ⤠i ⤠j ⤠N and multiply â1 by all elements of the subarray. Examples: Input: N = 5, A[] = [1, 5, -2, 3, -1]Outpu
6 min read
Number of Subsequences with Even and Odd Sum Given an array, find the number of subsequences whose sum is even and the number of subsequences whose sum is odd. Example: Input: arr[] = {1, 2, 2, 3} Output: EvenSum = 7, OddSum = 8 There are 2^{N}-1 possible subsequences. The subsequences with even sum is 1) {1, 3} Sum = 4 2) {1, 2, 2, 3} Sum = 8
15 min read