Number of subarrays with m odd numbers
Last Updated :
15 Jun, 2023
Given an array of n elements and an integer m, we need to write a program to find the number of contiguous subarrays in the array, which contains exactly m odd numbers.
Examples :
Input : arr = {2, 5, 6, 9}, m = 2
Output: 2
Explanation:
subarrays are [2, 5, 6, 9]
and [5, 6, 9]
Input : arr = {2, 2, 5, 6, 9, 2, 11}, m = 2
Output: 8
Explanation:
subarrays are [2, 2, 5, 6, 9],
[2, 5, 6, 9], [5, 6, 9], [2, 2, 5, 6, 9, 2],
[2, 5, 6, 9, 2], [5, 6, 9, 2], [6, 9, 2, 11]
and [9, 2, 11]
Naive Approach: The naive approach is to generate all possible subarrays and simultaneously checking for the subarrays with m odd numbers.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubarrays( int a[], int n, int m)
{
int count = 0;
for ( int i = 0; i < n; i++)
{
int odd = 0;
for ( int j = i; j < n; j++)
{
if (a[j] % 2)
odd++;
if (odd == m)
count++;
}
}
return count;
}
int main()
{
int a[] = { 2, 2, 5, 6, 9, 2, 11 };
int n = sizeof (a) / sizeof (a[0]);
int m = 2;
cout << countSubarrays(a, n, m);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int countSubarrays( int a[], int n, int m)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++)
{
int odd = 0 ;
for ( int j = i; j < n; j++)
{
if (a[j] % 2 != 0 )
odd++;
if (odd == m)
count++;
}
}
return count;
}
public static void main(String[] args)
{
int a[] = { 2 , 2 , 5 , 6 , 9 , 2 , 11 };
int n = a.length;
int m = 2 ;
System.out.println(countSubarrays(a, n, m));
}
}
|
Python3
def countSubarrays(a, n, m):
count = 0
for i in range (n):
odd = 0
for j in range (i, n):
if (a[j] % 2 ):
odd + = 1
if (odd = = m):
count + = 1
return count
a = [ 2 , 2 , 5 , 6 , 9 , 2 , 11 ]
n = len (a)
m = 2
print (countSubarrays(a, n, m))
|
C#
using System;
class GFG {
static int countSubarrays( int [] a, int n, int m)
{
int count = 0;
for ( int i = 0; i < n; i++)
{
int odd = 0;
for ( int j = i; j < n; j++)
{
if (a[j] % 2 == 0)
odd++;
if (odd == m)
count++;
}
}
return count;
}
public static void Main()
{
int [] a = { 2, 2, 5, 6, 9, 2, 11 };
int n = a.Length;
int m = 2;
Console.WriteLine(countSubarrays(a, n, m));
}
}
|
PHP
<?php
function countSubarrays( $a , $n , $m )
{
$count = 0;
for ( $i = 0; $i < $n ; $i ++)
{
$odd = 0;
for ( $j = $i ; $j < $n ; $j ++)
{
if ( $a [ $j ] % 2)
$odd ++;
if ( $odd == $m )
$count ++;
}
}
return $count ;
}
$a = array ( 2, 2, 5, 6, 9, 2, 11 );
$n = count ( $a );
$m = 2;
echo countSubarrays( $a , $n , $m );
?>
|
Javascript
<script>
function countSubarrays(a, n, m)
{
var count = 0;
for ( var i = 0; i < n; i++)
{
var odd = 0;
for ( var j = i; j < n; j++)
{
if (a[j] % 2 == 0)
odd++;
if (odd == m)
count++;
}
}
return count;
}
var a = [ 2, 2, 5, 6, 9, 2, 11 ];
var n = a.length;
var m = 2;
document.write(countSubarrays(a, n, m));
</script>
|
Time Complexity: O(n2)
Auxiliary Space : O(1)
Efficient Approach: An efficient approach is to while traversing, compute the prefix[] array. Prefix[i] stores the number of prefixes which has ‘i’ odd numbers in it. We increase the count of odd numbers if the array element is an odd one. When the count of odd numbers exceeds or is equal to m, add the number of prefixes which has “(odd-m)” numbers to the answer. At every step odd>=m, we calculate the number of subarrays formed till a particular index with the help of prefix array. prefix[odd-m] provides us with the number of prefixes which has “odd-m” odd numbers, which is added to the count to get the number of subarrays till the index.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubarrays( int a[], int n, int m)
{
int count = 0;
int prefix[n + 1] = { 0 };
int odd = 0;
for ( int i = 0; i < n; i++)
{
prefix[odd]++;
if (a[i] & 1)
odd++;
if (odd >= m)
count += prefix[odd - m];
}
return count;
}
int main()
{
int a[] = { 2, 2, 5, 6, 9, 2, 11 };
int n = sizeof (a) / sizeof (a[0]);
int m = 2;
cout << countSubarrays(a, n, m);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int countSubarrays( int a[], int n, int m)
{
int count = 0 ;
int prefix[] = new int [n + 1 ];
int odd = 0 ;
for ( int i = 0 ; i < n; i++)
{
prefix[odd]++;
if ((a[i] & 1 ) == 1 )
odd++;
if (odd >= m)
count += prefix[odd - m];
}
return count;
}
public static void main(String[] args)
{
int a[] = { 2 , 2 , 5 , 6 , 9 , 2 , 11 };
int n = a.length;
int m = 2 ;
System.out.println(countSubarrays(a, n, m));
}
}
|
Python3
def countSubarrays(a, n, m):
count = 0
prefix = [ 0 ] * (n + 1 )
odd = 0
for i in range (n):
prefix[odd] + = 1
if (a[i] & 1 ):
odd + = 1
if (odd > = m):
count + = prefix[odd - m]
return count
a = [ 2 , 2 , 5 , 6 , 9 , 2 , 11 ]
n = len (a)
m = 2
print (countSubarrays(a, n, m))
|
C#
using System;
class GFG {
public static int countSubarrays( int [] a, int n, int m)
{
int count = 0;
int [] prefix = new int [n + 1];
int odd = 0;
for ( int i = 0; i < n; i++)
{
prefix[odd]++;
if ((a[i] & 1) == 1)
odd++;
if (odd >= m)
count += prefix[odd - m];
}
return count;
}
public static void Main()
{
int [] a = { 2, 2, 5, 6, 9, 2, 11 };
int n = a.Length;
int m = 2;
Console.WriteLine(countSubarrays(a, n, m));
}
}
|
PHP
<?php
function countSubarrays(& $a , $n , $m )
{
$count = 0;
$prefix [ $n +1] = array ();
$odd = 0;
for ( $i = 0; $i < $n ; $i ++)
{
$prefix [ $odd ]++;
if ( $a [ $i ] & 1)
$odd ++;
if ( $odd >= $m )
$count += $prefix [ $odd - $m ];
}
return $count ;
}
$a = array (2, 2, 5, 6, 9, 2, 11 );
$n = sizeof( $a );
$m = 2;
echo countSubarrays( $a , $n , $m );
?>
|
Javascript
<script>
function countSubarrays(a, n, m)
{
let count = 0;
let prefix = new Array(n + 1);
prefix.fill(0);
let odd = 0;
for (let i = 0; i < n; i++)
{
prefix[odd]++;
if ((a[i] & 1) == 1)
odd++;
if (odd >= m)
count += prefix[odd - m];
}
return count;
}
let a = [ 2, 2, 5, 6, 9, 2, 11 ];
let n = a.length;
let m = 2;
document.write(countSubarrays(a, n, m));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Alternative approach: An alternative approach is to replace all the odd numbers with 1 and all the even numbers with zero and then calculate the number of subarrays with sum equal to m.
An efficient solution for this is while traversing the array, storing the sum so far in currsum. Also, maintain the count of different values of currsum in a map. If the value of currsum is equal to the desired sum at any instance, increment the count of subarrays by one.
The value of currsum exceeds the desired sum by currsum – sum. If this value is removed from currsum, the desired sum can be obtained. From the map, find the number of subarrays previously found having sum equal to currsum-sum. Excluding all those subarrays from the current subarray gives new subarrays having the desired sum.
So increase the count by the number of such subarrays. Note that when currsum is equal to the desired sum, check the number of subarrays previously having a sum equal to 0. Excluding those subarrays from the current subarray gives new subarrays having the desired sum. Increase the count by the number of subarrays having the sum of 0 in that case.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubarrays( int arr[], int n, int m)
{
unordered_map< int , int > prevSum;
int res = 0;
int currSum = 0;
for ( int i = 0; i < n; i++) {
currSum += arr[i];
if (currSum == m)
res++;
if (prevSum.find(currSum - m) != prevSum.end())
res += (prevSum[currSum - m]);
prevSum[currSum]++;
}
return res;
}
int main()
{
int a[] = { 2, 2, 5, 6, 9, 2, 11 };
int n = sizeof (a) / sizeof (a[0]);
int m = 2;
for ( int i = 0; i < n; i++) {
if (a[i] % 2 == 0)
a[i] = 0;
else
a[i] = 1;
}
cout << countSubarrays(a, n, m);
return 0;
}
|
Java
import java.util.*;
public class GFG {
static int countSubarrays( int arr[], int n, int m)
{
HashMap<Integer, Integer> prevSum = new HashMap<>();
int res = 0 ;
int currSum = 0 ;
for ( int i = 0 ; i < n; i++) {
currSum += arr[i];
if (currSum == m)
res++;
if (prevSum.containsKey(currSum - m))
res += (prevSum.get(currSum - m));
prevSum.put(currSum,
prevSum.getOrDefault(currSum, 0 )
+ 1 );
}
return res;
}
public static void main(String[] args)
{
int a[] = { 2 , 2 , 5 , 6 , 9 , 2 , 11 };
int n = a.length;
int m = 2 ;
for ( int i = 0 ; i < n; i++) {
if (a[i] % 2 == 0 )
a[i] = 0 ;
else
a[i] = 1 ;
}
System.out.println(countSubarrays(a, n, m));
}
}
|
Python3
def countSubarrays(arr, n, m):
prevSum = {}
res = currSum = 0
for i in range (n):
currSum + = arr[i]
if currSum = = m: res + = 1
if currSum - m in prevSum: res + = prevSum[currSum - m]
if currSum in prevSum: prevSum[currSum] + = 1
else : prevSum[currSum] = 1
return res
a = [ 2 , 2 , 5 , 6 , 9 , 2 , 11 ]
n = len (a)
m = 2
for i in range (n):
if (a[i] % 2 = = 0 ): a[i] = 0
else : a[i] = 1
print (countSubarrays(a, n, m))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
static int countSubarrays( int [] arr, int n, int m)
{
Dictionary< int , int > prevSum
= new Dictionary< int , int >();
int res = 0;
int currSum = 0;
for ( int i = 0; i < n; i++) {
currSum += arr[i];
if (currSum == m)
res++;
if (prevSum.ContainsKey(currSum - m))
res += (prevSum[currSum - m]);
if (prevSum.ContainsKey(currSum))
prevSum[currSum] = prevSum[currSum] + 1;
else
prevSum.Add(currSum, 1);
}
return res;
}
public static void Main( string [] args)
{
int [] a = { 2, 2, 5, 6, 9, 2, 11 };
int n = a.Length;
int m = 2;
for ( int i = 0; i < n; i++) {
if (a[i] % 2 == 0)
a[i] = 0;
else
a[i] = 1;
}
Console.WriteLine(countSubarrays(a, n, m));
}
}
|
Javascript
function countSubarrays(arr, n, m) {
const prevSum = new Map();
let res = 0;
let currSum = 0;
for (let i = 0; i < n; i++) {
currSum += arr[i];
if (currSum === m) res++;
if (prevSum.has(currSum - m)) res += prevSum.get(currSum - m);
prevSum.set(currSum, (prevSum.get(currSum) || 0) + 1);
}
return res;
}
function main() {
const a = [2, 2, 5, 6, 9, 2, 11];
const n = a.length;
const m = 2;
for (let i = 0; i < n; i++) {
if (a[i] % 2 === 0) a[i] = 0;
else a[i] = 1;
}
console.log(countSubarrays(a, n, m));
}
main();
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Another Approach:
Exactly(k) = atMost(k) – atMost(k-1)
While traversing, calculate the count of odd numbers. If count of odd numbers became greater than m, then increment the index i and check whether the arr[i] is an odd element or not. If arr[i] is odd then decrement the count of odd till the count of odd becomes equal to m. Store the length of subarray in ans.
Do the above process for subarrays with at most k odd elements and for the subarrays with at most k-1 odd elements.
If we subtract the subarrays with at most k-1 odd elements occur from the subarrays with at most k odd elements occur, we get exactly the subarrays with k odd elements.
C++
#include <bits/stdc++.h>
using namespace std;
int atMost( int arr[], int n, int m){
int i=0, ans=0, odd=0;
for ( int j=0;j<n;j++){
if (arr[j]%2==1){
odd++;
}
while (i<= j && odd>m){
if (arr[i]%2==1){
odd--;
}
i++;
}
ans+= j-i+1;
}
return ans;
}
int countSubarrays( int arr[], int n, int m){
return atMost(arr, n, m) - atMost(arr, n, m-1);
}
int main() {
int arr[] = { 2, 2, 5, 6, 9, 2, 11 };
int n = sizeof (arr) / sizeof (arr[0]);
int m = 2;
cout << countSubarrays(arr, n, m);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int atMost( int [] arr, int n, int m) {
int i = 0 , ans = 0 , odd = 0 ;
for ( int j = 0 ; j < n; j++) {
if (arr[j] % 2 == 1 ) {
odd++;
}
while (i <= j && odd > m) {
if (arr[i] % 2 == 1 ) {
odd--;
}
i++;
}
ans += j - i + 1 ;
}
return ans;
}
public static int countSubarrays( int [] arr, int n, int m) {
return atMost(arr, n, m) - atMost(arr, n, m- 1 );
}
public static void main(String[] args) {
int [] arr = { 2 , 2 , 5 , 6 , 9 , 2 , 11 };
int n = arr.length;
int m = 2 ;
System.out.println(countSubarrays(arr, n, m));
}
}
|
Python3
def atMost(arr, n, m):
i = 0
ans = 0
odd = 0
for j in range (n):
if arr[j] % 2 = = 1 :
odd + = 1
while i < = j and odd > m:
if arr[i] % 2 = = 1 :
odd - = 1
i + = 1
ans + = j - i + 1
return ans
def countSubarrays(arr, n, m):
return atMost(arr, n, m) - atMost(arr, n, m - 1 )
arr = [ 2 , 2 , 5 , 6 , 9 , 2 , 11 ]
n = len (arr)
m = 2
print (countSubarrays(arr, n, m))
|
C#
using System;
public class Program {
public static int AtMost( int [] arr, int n, int m) {
int i = 0, ans = 0, odd = 0;
for ( int j = 0; j < n; j++)
{
if (arr[j] % 2 == 1) {
odd++;
}
while (i<= j && odd > m)
{
if (arr[i] % 2 == 1) {
odd--;
}
i++;
}
ans += j - i + 1;
}
return ans;
}
public static int CountSubarrays( int [] arr, int n, int m)
{
return AtMost(arr, n, m) - AtMost(arr, n, m - 1);
}
public static void Main() {
int [] arr = { 2, 2, 5, 6, 9, 2, 11 };
int n = arr.Length;
int m = 2;
Console.WriteLine(CountSubarrays(arr, n, m));
}
}
|
Javascript
function atMost(arr, n, m) {
let i = 0;
let ans = 0;
let odd = 0;
for (let j = 0; j < n; j++) {
if (arr[j] % 2 === 1) {
odd++;
}
while (i<= j && odd > m) {
if (arr[i] % 2 === 1) {
odd--;
}
i++;
}
ans += j - i + 1;
}
return ans;
}
function countSubarrays(arr, n, m) {
return atMost(arr, n, m) - atMost(arr, n, m - 1);
}
const arr = [2, 2, 5, 6, 9, 2, 11];
const n = arr.length;
const m = 2;
console.log(countSubarrays(arr, n, m));
|
Time Complexity: O(n)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...