The Wayback Machine - https://web.archive.org/web/20240818165444/https://www.geeksforgeeks.org/count-subarrays-equal-number-1s-0s/
Open In App

Count subarrays with equal number of 1’s and 0’s

Last Updated : 29 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[] of size n containing 0 and 1 only. The problem is to count the subarrays having an equal number of 0’s and 1’s.

Examples:  

Input: arr[] = {1, 0, 0, 1, 0, 1, 1}
Output: 8
Explanation: The index range for the 8 sub-arrays are: (0, 1), (2, 3), (0, 3), (3, 4), (4, 5)(2, 5), (0, 5), (1, 6)

Input: arr = { 1, 0, 0, 1, 1, 0, 0, 1}
Output: 12

Count subarrays with equal number of 1’s and 0’s using Frequency Counting:

The problem is closely related to the Largest subarray with an equal number of 0’s and 1’s

Follow the steps below to implement the above idea:

  1. Consider all 0’s in arr[] as -1.
  2. Create a hash table that holds the count of each sum[i] value, where sum[i] = sum(arr[0]+..+arr[i]), for i = 0 to n-1.
  3. Now start calculating the cumulative sum and then we get an incremental count of 1 for that sum represented as an index in the hash table. Arrays of each pair of positions with the same value in the cumulative sum constitute a continuous range with an equal number of 1’s and 0’s.
  4. Now traverse the hash table and get the frequency of each element in the hash table. Let frequency be denoted as freq. For each freq > 1 we can choose any two pairs of indices of a sub-array by (freq * (freq – 1)) / 2 number of ways. Do the same for all freq and sum up the result will be the number of all possible sub-arrays containing the equal number of 1’s and 0’s.
  5. Also, add freq of the sum of 0 to the hash table for the final result.

Explanation: 
Considering all 0’s as -1. if sum[i] == sum[j], where sum[i] = sum(arr[0]+..+arr[i]) and sum[j] = sum(arr[0]+..+arr[j]) and ‘i’ is less than ‘j’, then sum(arr[i+1]+..+arr[j]) must be 0. It can only be 0 if arr(i+1, .., j) contains an equal number of 1’s and 0’s. 

Follow the steps below to implement the above approach:

C++




// C++ implementation to count subarrays with
// equal number of 1's and 0's
#include <bits/stdc++.h>
 
using namespace std;
 
// function to count subarrays with
// equal number of 1's and 0's
int countSubarrWithEqualZeroAndOne(int arr[], int n)
{
    // 'um' implemented as hash table to store
    // frequency of values obtained through
    // cumulative sum
    unordered_map<int, int> um;
    int curr_sum = 0;
 
    // Traverse original array and compute cumulative
    // sum and increase count by 1 for this sum
    // in 'um'. Adds '-1' when arr[i] == 0
    for (int i = 0; i < n; i++) {
        curr_sum += (arr[i] == 0) ? -1 : arr[i];
        um[curr_sum]++;
    }
 
    int count = 0;
    // traverse the hash table 'um'
    for (auto itr = um.begin(); itr != um.end(); itr++) {
 
        // If there are more than one prefix subarrays
        // with a particular sum
        if (itr->second > 1)
            count
                += ((itr->second * (itr->second - 1)) / 2);
    }
 
    // add the subarrays starting from 1st element and
    // have equal number of 1's and 0's
    if (um.find(0) != um.end())
        count += um[0];
 
    // required count of subarrays
    return count;
}
 
// Driver program to test above
int main()
{
    int arr[] = { 1, 0, 0, 1, 0, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Count = "
         << countSubarrWithEqualZeroAndOne(arr, n);
    return 0;
}


Java




// Java implementation to count subarrays with
// equal number of 1's and 0's
import java.util.*;
 
class GFG {
 
    // function to count subarrays with
    // equal number of 1's and 0's
    static int countSubarrWithEqualZeroAndOne(int arr[],
                                              int n)
    {
        // 'um' implemented as hash table to store
        // frequency of values obtained through
        // cumulative sum
        Map<Integer, Integer> um = new HashMap<>();
        int curr_sum = 0;
 
        // Traverse original array and compute cumulative
        // sum and increase count by 1 for this sum
        // in 'um'. Adds '-1' when arr[i] == 0
        for (int i = 0; i < n; i++) {
            curr_sum += (arr[i] == 0) ? -1 : arr[i];
            um.put(curr_sum, um.get(curr_sum) == null
                                 ? 1
                                 : um.get(curr_sum) + 1);
        }
 
        int count = 0;
 
        // traverse the hash table 'um'
        for (Map.Entry<Integer, Integer> itr :
             um.entrySet()) {
 
            // If there are more than one prefix subarrays
            // with a particular sum
            if (itr.getValue() > 1)
                count += ((itr.getValue()
                           * (itr.getValue() - 1))
                          / 2);
        }
 
        // add the subarrays starting from 1st element and
        // have equal number of 1's and 0's
        if (um.containsKey(0))
            count += um.get(0);
 
        // required count of subarrays
        return count;
    }
 
    // Driver program to test above
    public static void main(String[] args)
    {
        int arr[] = { 1, 0, 0, 1, 0, 1, 1 };
        int n = arr.length;
        System.out.println(
            "Count = "
            + countSubarrWithEqualZeroAndOne(arr, n));
    }
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 implementation to count
# subarrays with equal number
# of 1's and 0's
 
# function to count subarrays with
# equal number of 1's and 0's
 
 
def countSubarrWithEqualZeroAndOne(arr, n):
 
    # 'um' implemented as hash table
    # to store frequency of values
    # obtained through cumulative sum
    um = dict()
    curr_sum = 0
 
    # Traverse original array and compute
    # cumulative sum and increase count
    # by 1 for this sum in 'um'.
    # Adds '-1' when arr[i] == 0
    for i in range(n):
        curr_sum += (-1 if (arr[i] == 0) else arr[i])
        if um.get(curr_sum):
            um[curr_sum] += 1
        else:
            um[curr_sum] = 1
 
    count = 0
 
    # traverse the hash table 'um'
    for itr in um:
 
        # If there are more than one
        # prefix subarrays with a
        # particular sum
        if um[itr] > 1:
            count += ((um[itr] * int(um[itr] - 1)) / 2)
 
    # add the subarrays starting from
    # 1st element and have equal
    # number of 1's and 0's
    if um.get(0):
        count += um[0]
 
    # required count of subarrays
    return int(count)
 
 
# Driver code to test above
arr = [1, 0, 0, 1, 0, 1, 1]
n = len(arr)
print("Count =",
      countSubarrWithEqualZeroAndOne(arr, n))
 
# This code is contributed by "Sharad_Bhardwaj".


C#




// C# implementation to count subarrays
// with equal number of 1's and 0's
using System;
using System.Collections.Generic;
 
class GFG {
 
    // function to count subarrays with
    // equal number of 1's and 0's
    static int countSubarrWithEqualZeroAndOne(int[] arr,
                                              int n)
    {
        // 'um' implemented as hash table to store
        // frequency of values obtained through
        // cumulative sum
        Dictionary<int, int> mp
            = new Dictionary<int, int>();
        int curr_sum = 0;
 
        // Traverse original array and compute cumulative
        // sum and increase count by 1 for this sum
        // in 'um'. Adds '-1' when arr[i] == 0
        for (int i = 0; i < n; i++) {
            curr_sum += (arr[i] == 0) ? -1 : arr[i];
            if (mp.ContainsKey(curr_sum)) {
                var v = mp[curr_sum];
                mp.Remove(curr_sum);
                mp.Add(curr_sum, ++v);
            }
            else
                mp.Add(curr_sum, 1);
        }
 
        int count = 0;
 
        // traverse the hash table 'um'
        foreach(KeyValuePair<int, int> itr in mp)
        {
 
            // If there are more than one prefix subarrays
            // with a particular sum
            if (itr.Value > 1)
                count
                    += ((itr.Value * (itr.Value - 1)) / 2);
        }
 
        // add the subarrays starting from 1st element
        // and have equal number of 1's and 0's
        if (mp.ContainsKey(0))
            count += mp[0];
 
        // required count of subarrays
        return count;
    }
 
    // Driver program to test above
    public static void Main(String[] args)
    {
        int[] arr = { 1, 0, 0, 1, 0, 1, 1 };
        int n = arr.Length;
        Console.WriteLine(
            "Count = "
            + countSubarrWithEqualZeroAndOne(arr, n));
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// Javascript implementation to count subarrays with
// equal number of 1's and 0's
 
// function to count subarrays with
// equal number of 1's and 0's
function countSubarrWithEqualZeroAndOne(arr, n)
{
    // 'um' implemented as hash table to store
    // frequency of values obtained through
    // cumulative sum
    var um = new Map();
    var curr_sum = 0;
 
    // Traverse original array and compute cumulative
    // sum and increase count by 1 for this sum
    // in 'um'. Adds '-1' when arr[i] == 0
    for (var i = 0; i < n; i++) {
        curr_sum += (arr[i] == 0) ? -1 : arr[i];
        if(um.has(curr_sum))
            um.set(curr_sum, um.get(curr_sum)+1);
        else
            um.set(curr_sum, 1)
    }
 
    var count = 0;
    // traverse the hash table 'um'
    um.forEach((value, key) => {
         
        // If there are more than one prefix subarrays
        // with a particular sum
        if (value > 1)
            count += ((value * (value - 1)) / 2);
    });
 
    // add the subarrays starting from 1st element and
    // have equal number of 1's and 0's
    if (um.has(0))
        count += um.get(0);
 
    // required count of subarrays
    return count;
}
 
// Driver program to test above
var arr = [1, 0, 0, 1, 0, 1, 1];
var n = arr.length;
document.write( "Count = "
      + countSubarrWithEqualZeroAndOne(arr, n));
 
// This code is contributed by noob2000.
</script>


PHP




<?php
// Php program for the above approach
// Function to count subarrays with equal number of 1's and 0's
function countSubarrWithEqualZeroAndOne($arr, $n) {
    // 'um' implemented as hash table to store
    // frequency of values obtained through
    // cumulative sum
    $um = array();
    $curr_sum = 0;
 
    // Traverse original array and compute cumulative
    // sum and increase count by 1 for this sum
    // in 'um'. Adds '-1' when $arr[$i] == 0
    for ($i = 0; $i < $n; $i++) {
        $curr_sum += ($arr[$i] == 0) ? -1 : $arr[$i];
        $um[$curr_sum]++;
    }
 
    $count = 0;
 
    // Traverse the hash table 'um'
    foreach ($um as $value) {
        // If there are more than one prefix subarrays
        // with a particular sum
        if ($value > 1) {
            $count += (($value * ($value - 1)) / 2);
        }
    }
 
    // Add the subarrays starting from 1st element and
    // have an equal number of 1's and 0's
    if (array_key_exists(0, $um)) {
        $count += $um[0];
    }
 
    // Required count of subarrays
    return $count;
}
 
// Driver program to test above
$arr = array(1, 0, 0, 1, 0, 1, 1);
$n = count($arr);
echo "Count = " . countSubarrWithEqualZeroAndOne($arr, $n);
 
?>


Output

Count = 8

Time Complexity: O(N), where N is the length of the given array
Auxiliary Space: O(N). 

Count subarrays with equal number of 1’s and 0’s using Map:

Follow the steps below for implementation:

  • Create a map say mp.
  • Iterate over the length of the given array
    • Check if arr[i] == 0, then replace it with -1.
    • Keep calculating the number into sum till ith index.
    • If sum = 0, it implies the number of 0’s and 1’s are equal from arr[0]..arr[i]
    • if mp[sum] exists then add “frequency-1” to count
    • if the frequency of “sum” is zero then we initialize that frequency to 1, f it’s not 0, we increment it
  • Finally, return the count.

Follow the steps below to implement the above approach:

C++




#include <bits/stdc++.h>
 
using namespace std;
 
int countSubarrWithEqualZeroAndOne(int arr[], int n)
{
    unordered_map<int, int> mp;
    int sum = 0;
    int count = 0;
    for (int i = 0; i < n; i++) {
        // Replacing 0's in array with -1
        if (arr[i] == 0)
            arr[i] = -1;
 
        sum += arr[i];
 
        // If sum = 0, it implies number of 0's and 1's are
        // equal from arr[0]..arr[i]
        if (sum == 0)
            count++;
 
        // if mp[sum] exists then add "frequency-1" to count
        if (mp[sum])
            count += mp[sum];
 
        // if frequency of "sum" is zero then we initialize
        // that frequency to 1 if its not 0, we increment it
        if (mp[sum] == 0)
            mp[sum] = 1;
        else
            mp[sum]++;
    }
    return count;
}
 
int main()
{
    int arr[] = { 1, 0, 0, 1, 0, 1, 1 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << "count="
         << countSubarrWithEqualZeroAndOne(arr, n);
}


Java




import java.util.HashMap;
import java.util.Map;
 
// Java implementation to count subarrays with
// equal number of 1's and 0's
public class Main {
 
    // Function that returns count of sub arrays
    // with equal numbers of 1's and 0's
    static int countSubarrWithEqualZeroAndOne(int[] arr,
                                              int n)
    {
        Map<Integer, Integer> myMap = new HashMap<>();
        int sum = 0;
        int count = 0;
        for (int i = 0; i < n; i++) {
            // Replacing 0's in array with -1
            if (arr[i] == 0)
                arr[i] = -1;
 
            sum += arr[i];
 
            // If sum = 0, it implies number of 0's and 1's
            // are equal from arr[0]..arr[i]
            if (sum == 0)
                count++;
 
            if (myMap.containsKey(sum))
                count += myMap.get(sum);
 
            if (!myMap.containsKey(sum))
                myMap.put(sum, 1);
            else
                myMap.put(sum, myMap.get(sum) + 1);
        }
        return count;
    }
 
    // main function
    public static void main(String[] args)
    {
        int arr[] = { 1, 0, 0, 1, 0, 1, 1 };
        int n = arr.length;
        System.out.println(
            "Count = "
            + countSubarrWithEqualZeroAndOne(arr, n));
    }
}


Python3




# Python3 implementation to count subarrays
# with equal number of 1's and 0's
 
 
def countSubarrWithEqualZeroAndOne(arr, n):
    mp = dict()
    Sum = 0
    count = 0
 
    for i in range(n):
 
        # Replacing 0's in array with -1
        if (arr[i] == 0):
            arr[i] = -1
 
        Sum += arr[i]
 
        # If Sum = 0, it implies number of
        # 0's and 1's are equal from arr[0]..arr[i]
        if (Sum == 0):
            count += 1
 
        if (Sum in mp.keys()):
            count += mp[Sum]
 
        mp[Sum] = mp.get(Sum, 0) + 1
 
    return count
 
 
# Driver Code
arr = [1, 0, 0, 1, 0, 1, 1]
 
n = len(arr)
 
print("count =",
      countSubarrWithEqualZeroAndOne(arr, n))
 
# This code is contributed by mohit kumar


C#




// C# implementation to count subarrays with
// equal number of 1's and 0's
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Function that returns count of sub arrays
    // with equal numbers of 1's and 0's
    static int countSubarrWithEqualZeroAndOne(int[] arr,
                                              int n)
    {
        Dictionary<int, int> myMap
            = new Dictionary<int, int>();
        int sum = 0;
        int count = 0;
        for (int i = 0; i < n; i++) {
            // Replacing 0's in array with -1
            if (arr[i] == 0)
                arr[i] = -1;
 
            sum += arr[i];
 
            // If sum = 0, it implies number of 0's and 1's
            // are equal from arr[0]..arr[i]
            if (sum == 0)
                count++;
 
            if (myMap.ContainsKey(sum))
                count += myMap[sum];
 
            if (!myMap.ContainsKey(sum))
                myMap.Add(sum, 1);
            else {
                var v = myMap[sum] + 1;
                myMap.Remove(sum);
                myMap.Add(sum, v);
            }
        }
        return count;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 1, 0, 0, 1, 0, 1, 1 };
        int n = arr.Length;
        Console.WriteLine(
            "Count = "
            + countSubarrWithEqualZeroAndOne(arr, n));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
  
// Javascript implementation to count subarrays with
// equal number of 1's and 0's
 
function countSubarrWithEqualZeroAndOne(arr, n)
{
    var mp = new Map();
    var sum = 0;
    let count = 0;
     
    for (var i = 0; i < n; i++) {
        //Replacing 0's in array with -1
        if (arr[i] == 0)
            arr[i] = -1;
  
        sum += arr[i];
  
        //If sum = 0, it implies number of 0's and 1's are
        //equal from arr[0]..arr[i]
        if (sum == 0)
            count += 1;
  
        if (mp.has(sum) == true)
            count += mp.get(sum);
                 
        if(mp.has(sum) == false)
            mp.set(sum, 1);
        else
            mp.set(sum, mp.get(sum)+1);
    }
      return count;
}
  
// Driver program to test above
var arr = [1, 0, 0, 1, 0, 1, 1];
var n = arr.length;
document.write( "Count = "
      + countSubarrWithEqualZeroAndOne(arr, n));
  
// This code is contributed by noob2000.
</script>


PHP




<?php
//Php code for the above approach
// Function to count subarrays with equal number of 1's and 0's
function countSubarrWithEqualZeroAndOne($arr, $n) {
    // Initialize an associative array to store the cumulative sum frequencies
    $mp = array();
    $sum = 0;
    $count = 0;
 
    // Traverse the array
    for ($i = 0; $i < $n; $i++) {
        // Replacing 0's in the array with -1
        if ($arr[$i] == 0) {
            $arr[$i] = -1;
        }
 
        $sum += $arr[$i];
 
        // If sum = 0, it implies the number of 0's and 1's are
        // equal from $arr[0]..$arr[$i]
        if ($sum == 0) {
            $count++;
        }
 
        // If $mp[$sum] exists, then add "frequency-1" to count
        if (isset($mp[$sum])) {
            $count += $mp[$sum];
        }
 
        // If frequency of $sum is zero, then initialize that frequency to 1,
        // if it's not zero, increment it
        if (!isset($mp[$sum])) {
            $mp[$sum] = 1;
        } else {
            $mp[$sum]++;
        }
    }
 
    // Return the final count of subarrays
    return $count;
}
 
// Driver program to test above
$arr = array(1, 0, 0, 1, 0, 1, 1);
$n = count($arr);
echo "Count = " . countSubarrWithEqualZeroAndOne($arr, $n);
 
?>


Output

count=8

Time Complexity: O(N), where N is the length of the given array
Auxiliary Space: O(N).



Similar Reads

Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements
Given two arrays A[] and B[], and an integer K, the task is to find the number of ways to select two subarrays of the same size, one from A and the other one from B such that the subarrays have at least K equal pairs of elements. (i.e. the number of pairs (A[i], B[j]) in the two selected subarrays such that A[i] = B[j] &gt;= K). Examples: Input: A[
13 min read
Count subarrays having an equal count of 0s and 1s segregated
Given a binary array arr[], the task is to count the number of subarrays having equal count of 0s and 1s, and all the 0s and 1s are placed consecutively in that subarray. Examples: Input: arr[] = {1, 0, 1, 1}Output: 2Explanation: The subarrays satisfying the given conditions are {1, 0} and {0, 1}. Therefore, the count of such subarrays is 2. Input:
10 min read
Count subarrays with equal count of occurrences of given three numbers
Given an array arr[] and three integers X, Y, Z, the task is to find the number of subarrays from the array in which the number of occurrences of X, Y and Z are equal. Examples: Input: arr[] = {3, 6, 7, 8, 3, 6, 7}, X = 3, Y = 6, Z = 7Output: 8Explanationn: There are 8 such subarrays i.e. {3, 6, 7}, {6, 7, 8, 3}, {7, 8, 3, 6}, {8}, {3, 6, 7, 8}, {8
9 min read
Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times
Given an array arr[] consisting of N integers, the task is to find the number of different sequences that can be formed after performing the below operation on the given array arr[] any number of times. Choose two indices i and j such that arr[i] is equal to arr[j] and update all the elements in the range [i, j] in the array to arr[i]. Examples: In
7 min read
Differences between number of increasing subarrays and decreasing subarrays in k sized windows
Given an array of integers and k, find the difference between the number of the strictly increasing number of subarrays (of size more than one) and the number of the strictly decreasing subarray in the window of size k. Examples: Input : nums = {10, 20, 30, 15, 15}; k = 3; Output : 3, 0, -1 Explanation For the first window of [10, 20, 30], there ar
8 min read
Count of binary strings of length N having equal count of 0's and 1's and count of 1's &ge; count of 0's in each prefix substring
Given an integer N, the task is to find the number of possible binary strings of length N with an equal frequency of 0's and 1's in which frequency of 1's are greater or equal to the frequency of 0's in every prefix substring. Examples: Input: N = 2Output: 1Explanation:All possible binary strings of length 2 are {"00", "01", "10" and "11"}. Out of
7 min read
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
Count subarrays with equal number of occurrences of two given elements
Given an array and two integers say, x and y, find the number of subarrays in which the number of occurrences of x is equal to the number of occurrences of y. Examples: Input : arr[] = {1, 2, 1}, x = 1, y = 2 Output : 2 The possible sub-arrays have same equal number of occurrences of x and y are: 1) {1, 2}, x and y have same occurrence(1). 2) {2, 1
14 min read
Split given Array in minimum number of subarrays such that rearranging the order of subarrays sorts the array
Given an array arr[] consisting of N integers, the task is to find the minimum number of splitting of array elements into subarrays such that rearranging the order of subarrays sorts the given array. Examples: Input: arr[] = {6, 3, 4, 2, 1}Output: 4Explanation:The given array can be divided into 4 subarrays as {6}, {3, 4}, {2}, {1} and these subarr
7 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 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
Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays
Given an array arr[] consisting of N integers, the task is to maximize the sum of the difference of the maximum and minimum in each subarrays by splitting the given array into non-overlapping subarrays. Examples: Input: arr[] = {8, 1, 7, 9, 2}Output: 14Explanation:Split the given array arr[] as {8, 1}, {7, 9, 2}. Now, the sum of the difference maxi
7 min read
Count of subarrays whose product is equal to difference of two different numbers
Given a non-negative array a, the task is to find the count of subarrays whose product of elements can be represented as the difference of two different numbers. Examples: Input: arr = {2, 5, 6} Output: 2 Explanation: Product of elements of subarray {5} can be represented as 32 - 22 is equal to 5 Product of elements of subarray {2, 5, 6} can be rep
13 min read
Count subarrays with sum equal to its XOR value
Given an array arr[] containing N elements, the task is to count the number of sub-arrays whose XOR of all the elements is equal to the sum of all the elements in the subarray. Examples: Input: arr[] = {2, 5, 4, 6} Output: 5 Explanation: All the subarrays {{2}, {5}, {4}, {6}} satisfies the above condition since the XOR of the subarrays is same as t
10 min read
Count of subarrays having sum equal to its length
Given an array arr[] of size N, the task is to find the number of subarrays having the sum of its elements equal to the number of elements in it. Examples: Input: N = 3, arr[] = {1, 0, 2}Output: 3Explanation:Total number of subarrays are 6 i.e., {1}, {0}, {2}, {1, 0}, {0, 2}, {1, 0, 2}.Out of 6 only three subarrays have the number of elements equal
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 of subarrays having sum equal to its length | Set 2
Given an array arr[] of size N, the task is to find the number of subarrays having sum of its elements equal to the number of elements in it. Examples: Input: N = 3, arr[] = {1, 0, 2}Output: 3Explanation:Total number of subarrays are 6 i.e., {1}, {0}, {2}, {1, 0}, {0, 2}, {1, 0, 2}.Out of the 6 subarrays, following three subarrays satisfy the given
7 min read
Count ways to split array into two equal sum subarrays by replacing each array element to 0 once
Given an array arr[] consisting of N integers, the task is to count the number of ways to split the array into two subarrays of equal sum after changing a single array element to 0. Examples: Input: arr[] = {1, 2, -1, 3}Output: 4Explanation: Replacing arr[0] by 0, arr[] is modified to {0, 2, -1, 3}. Only 1 possible split is {0, 2} and {-1, 3}. Repl
11 min read
Count ways to split array into two subarrays with equal GCD
Given an array, arr[] of size N, the task is to count the number of ways to split given array elements into two subarrays such that GCD of both the subarrays are equal. Examples: Input: arr[] = {8, 4, 4, 8, 12} Output: 2 Explanation: Possible ways to split the array two groups of equal GCD are: { {{arr[0], arr[1]}, {arr[2], arr[3], arr[4]}}, {{arr[
8 min read
Count ways to split array into two equal sum subarrays by changing sign of any one array element
Given an array arr[] consisting of N integers, the task is to count ways to split array into two subarrays of equal sum by changing the sign of any one array element. Examples: Input: arr[] = {2, 2, -3, 3}Output: 2Explanation:Changing arr[0] = 2 to arr[0] = -2, the array becomes {-2, 2, -3, 3}. Only 1 possible split is {-2, 2} and {-3, 3}.Changing
11 min read
Count ways to split array into three non-empty subarrays having equal Bitwise XOR values
Given an array arr[] consisting of N non-negative integers, the task is to count the number of ways to split the array into three different non-empty subarrays such that Bitwise XOR of each subarray is equal. Examples: Input: arr[] = {7, 0, 5, 2, 7} Output: 2Explanation: All possible ways are:{{7}, {0, 5, 2}, {7}} where XOR value of each subarray i
9 min read
Count unordered pairs of equal elements for all subarrays
Given an array arr[] consisting of N integers, the task is to find the total number of unordered pairs (i, j) in the array such that arr[i] is equal to arr[j] and i &lt; j for all subarrays of the given array. Examples: Input: arr[] = {1, 2, 1, 1}Output: 6Explanation: All subarrays of the given array of size greater than 1 are: {1, 2}: There are no
7 min read
Count of subarrays in range [L, R] having XOR + 1 equal to XOR (XOR) 1 for M queries
Given an array, arr[] of N positive integers and M queries which consist of two integers [Li, Ri] where 1 ? Li ? Ri ? N. For each query, find the number of subarrays in range [Li, Ri] for which (X+1)=(X?1) where X denotes the xor of a subarray. Input: arr[]= {1, 2, 9, 8, 7}, queries[] = {{1, 5}, {3, 4}}Output: 6 1Explanation: Query 1: L=1, R=5: sub
12 min read
Count non-overlapping Subarrays of size K with equal alternate elements
Given an array arr[] of length N, the task is to find the count of non-overlapping subarrays of size K such that the alternate elements are equal. Examples: Input: arr[] = {2, 4, 2, 7}, K = 3Output: 1Explanation: Given subarray {2, 4, 2} is a valid array because the elements in even position(index no.0 and 2) are equal. Hence the count of the subar
7 min read
Split array into K subarrays such that sum of maximum of all subarrays is maximized
Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print "-1". Examples: Input: arr[] = {5, 3, 2, 7, 6, 4},
11 min read
Check if Array can be split into subarrays such that XOR of length of Longest Decreasing Subsequences of those subarrays is 0
Given an array of integers arr[] of size N, the task is to check whether arr[] can be split into different subarrays such that on taking the XOR of lengths of LDS (Longest decreasing subsequences) of all the subarrays is equal to 0. Print 'YES' if it is possible to split else print 'NO'. Examples: Input: arr[] = {1, 0, 3, 4, 5}Output: YESExplanatio
6 min read
Split into K subarrays to minimize the maximum sum of all subarrays
Given an Array[] of N elements and a number K. ( 1 &lt;= K &lt;= N ) . Split the given array into K subarrays (they must cover all the elements). The maximum subarray sum achievable out of K subarrays formed, must be the minimum possible. Find that possible subarray sum.Examples: Input : Array[] = {1, 2, 3, 4}, K = 3 Output : 4 Optimal Split is {1,
15 min read
Number of subarrays for which product and sum are equal
Given a array of n numbers. We need to count the number of subarrays having the product and sum of elements are equal Examples: Input : arr[] = {1, 3, 2} Output : 4 The subarrays are : [0, 0] sum = 1, product = 1, [1, 1] sum = 3, product = 3, [2, 2] sum = 2, product = 2 and [0, 2] sum = 1+3+2=6, product = 1*3*2 = 6 Input : arr[] = {4, 1, 2, 1} Outp
5 min read
Number of subarrays with GCD equal to 1
Given an array arr[], the task is to find the number of sub-arrays with a GCD value equal to 1. Examples: Input: arr[] = {1, 1, 1} Output: 6 All the subarrays of the given array will have GCD equal to 1.Input: arr[] = {2, 2, 2} Output: 0 Approach: The key observation is that if the GCD of all the elements of the sub-array arr[l...r] is known then t
5 min read
Number of times an array can be partitioned repetitively into two subarrays with equal sum
Given an array arr[] of size N, the task is to find the number of times the array can be partitioned repetitively into two subarrays such that the sum of the elements of both the subarrays is the same. Examples: Input: arr[] = { 2, 2, 2, 2 } Output: 3 Explanation: 1. Make the first partition after index 1. Remaining arrays are {2, 2} on the right s
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg