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.
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.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 100
1 <= N <= 5 * 10^3
0 <= ARR[i] <= 1
Time limit: 1 sec
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.
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: