Given a binary array containing 0’s and 1’s, find the largest subarray with equal numbers of 0’s and 1’s.

For example,

Input:  { 0, 0, 1, 0, 1, 0, 0 }
 
Output: Largest subarray is { 0, 1, 0, 1 } or { 1, 0, 1, 0 }

Practice this problem

The problem differs from the problem of finding the largest subsequence with equal numbers of 0’s and 1’s. Unlike subsequences, subarrays are required to occupy consecutive positions within the original array.

 
A naive solution would be to consider all subarrays and, for each subarray, count the total number of 0’s and 1’s present. If the subarray contains an equal number of 0’s and 1’s, update the largest subarray if required. The time complexity of the naive solution is O(n3) as there are n2 subarrays in an array of size n, and it takes O(n) time to find count 0’s and 1’s. We can optimize the method to run in O(n2) time by calculating the count of 0’s and 1’s in constant time.

 
We can use the map to solve this problem in linear time. The idea is to replace 0 with -1 and find out the largest subarray with a sum of 0. To find the largest subarray with a sum of 0, create an empty map that stores the first subarray’s ending index having a given sum. Then traverse the given array and maintain the sum of elements seen so far.

  • If the sum is seen for the first time, insert the sum with its index into the map.
  • If the sum is seen before, there exists a subarray with a sum of 0, which ends at the current index, and update the largest subarray if the current subarray has more length.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

[1, 4]

Java


Download  Run Code

Output:

[1, 4]

Python


Download  Run Code

Output:

(1, 4)

The time complexity of the above solution O(n) and requires O(n) extra space, where n is the size of the input.