Last Updated: 30 Oct, 2020

Largest subarray with equal number of 0s and 1s

Moderate
Asked in companies
OraclePhonePeSAP Labs

Problem statement

You are given an array consisting of 0s and 1s. You need to find the length of the largest subarray with an equal number of 0s and 1s.

For example:

If the given array is: [0, 0, 1, 0, 1] The largest subarray would be: [0, 1, 0, 1] (last 4 elements) having length 4.
Input Format:
The first line of input contains a single integer T, representing the number of test cases or queries to be run. 
Then the T test cases follow.

The first line of each test case contains a single integer N denoting the length of the array.

The second line of each test case contains N space-separated integers representing the array elements.
Output Format:
For each test case, return the length of the largest subarray with the equal number of 0s and 1s, in a new 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 ≤ 10
1 ≤ N ≤ 10^5
0 ≤ Ai ≤ 1

Time Limit : 1 sec 

Approaches

01 Approach

  • We generate all the possible subarrays by using two nested loops.
  • We can run two nested loops, the outer loop picks the starting element and the inner loop picks the ending element.
  • The third loop considers all elements in between the starting and ending elements.
  • Check if each subarray has equal number of 0s and 1s
  • This can be easily done by considering 0 as -1 and 1 as 1 since the sum for equal numbers of 0s and 1s would be 0.
  • For all subarrays with equal numbers of 0s and 1s, we take the one with the largest length.

02 Approach

  • We generate all the possible subarrays by using nested loops.
  • We can run two nested loops, the outer loop picks the starting element and the inner loop considers all elements on the right of the picked elements as the ending element of the subarray.
  • Check if each subarray has equal number of 0s and 1s
  • This can be easily done by considering 0 as -1 and 1 as 1 since the sum for equal numbers of 0s and 1s would be 0.
  • For all subarrays with equal numbers of 0s and 1s, we take the one with the largest length.

03 Approach

  • For simplicity, consider 0 as -1 and 1 as 1 since the sum for equal numbers of 0s and 1s would be 0.
  • Store the cumulative sums in a hashmap. There can be two cases:
    • When cumulative sum is 0: This means that the subarray from index 0 to the present index has equal number of 0s and 1s
    • When cumulative sum is not equal to 0: This means that the subarray from the index which had this sum before to the present index has equal number of 0s and 1s
  • Note that you only need to store the first occurrence of each sum, since we need to find the largest subarray.