04 Subarrays with equal 0s and 1s

Question

Given an array of 0s and 1s. Find the length of the largest subarray with an equal number of 0s and 1s.

Example 1:

Input:
N = 4
A[] = {0,1,0,1}
Output: 4
Explanation: The array from index [0...3]
contains equal number of 0's and 1's.
Thus maximum length of subarray having
equal number of 0's and 1's is 4.

Example 2:

Input:
N = 5
A[] = {0,0,1,0,0}
Output: 2

Using map and subarray sum 0 zero approach

Logic
  1. For given input 0 0 1 0 0

  2. Assume 0s as -1 and 1s as 1

  3. The input becomes -1 -1 1 -1 -1

  4. Take The prefix Sum

  5. -1 -2 -1 -2 -3

  6. Wherever the prefix sum is 0

    1. We know that sum of prefix from the beginning to that position is 0

  7. Whenever we find two same prefix sum

    1. We know that the sum of elements after the first occurrence and the last occurrence is 0

  8. The sum being 0 implies that there are an equal number of -1 and 1

    1. Which in turn implies that there are an equal number of 0s and 1s

Code
Complexity

Time Complexity: O(n)O(n)

Space Complexity: O(n)O(n)

Last updated