Last Updated: 5 Nov, 2020

Subarray with equal occurrences

Moderate
Asked in companies
AmazonAmdocs

Problem statement

You have been given an array/list ARR of length N consisting of 0s and 1s only. Your task is to find the number of subarrays(non-empty) in which the number of 0s and 1s are equal.

Input Format:
The first line contains an integer 'T' denoting the number of test cases. Then each test case follows.

The first line of each test case contains a positive integer ‘N’ which represents the length of the array/list.

The second line of each test case contains ‘N’ single space-separated integers representing the elements of the array/list.
Output Format:
For each test case, the only line of output will print the number of subarrays in which the number of 0s and 1s are equal. 

Print the output of each test case in a separate line.

Note:

You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 100
1 <= N <= 5 * 10^3
0 <= ARR[i] <= 1

Time limit: 1 sec

Approaches

01 Approach

We will visit every subarray using two nested loops and maintain the count of 0s and 1s for each of them. Count of all the subarrays with equal 0s and 1s will be maintained in a ‘RESULT’ variable.

02 Approach

If we consider every ‘0’ as -1, then a subarray containing equal 0s and 1s will give a sum of 0. So, we can use the cumulative sum to count these subarrays with sum 0 easily. 

 

The idea is based on the fact that if a cumulative sum appears again in the array, then the subarray between these two occurrences of cumulative sum, will have a sum of 0. 

 

For example-
Given ARR   = [1, 1, 1, 0, 0, 1]

Cumu. Sum  = [1, 2, 3, 2, 1, 2]

 

Here, one of the required subarrays has index range[1, 4]. We can see that 1 appears again in the cumulative sum at index 4 (previously at index 0). Hence, the subarray between index 0(exclusive) and index 4(inclusive) is one of the subarrays with equal 0s and 1s.

 

Here is the algorithm:

  1. We will maintain ‘RESULT’ to count subarrays with equal 0s and 1s.
  2. We will initialise ‘CUMULATIVE’ to 0 to store the cumulative sum.
  3. Declare a hashtable ‘FREQUENCY’ that stores the frequency of the cumulative sum.
    1. Initialise FREQUENCY[0] by 1 as the cumulative sum of the empty array is 0.
  4. Now start iterating over the array and calculate the cumulative sum.
    1. If ARR[i] == 1, we increment ‘CUMULATIVE’ by 1.
    2. Else, we decrement it by 1.
    3. Add FREQUENCY[CUMULATIVE] to RESULT. This is because the total subarrays ending on the current element with sum 0 is given by FREQUENCY[CUMULATIVE].
    4. Increment FREQUENCY[CUMULATIVE] by 1.