AceYourInterviews
Checking sign-in…

31. Contiguous Array — Equal Zeroes and Ones

IntermediateEarliest repeated prefix balance

Find the longest continuous part of the array containing exactly as many zeros as ones. Return its length rather than the positions or the values of that part.

The required counts must match within the same range. A balanced selection of scattered positions is not a valid subarray.

Example 1

Input

[0,1,0]

Output

2

Explanation: Either [0,1] or [1,0] has one occurrence of each symbol.

Example 2

Input

[0,0,1,0,1,1]

Output

6

Explanation: The entire array has three zeros and three ones.

Constraints

  • 0 <= nums.length <= 105
  • nums[i] is 0 or 1
Hints
Hint 1

What signed contribution makes equal zero/one counts sum to zero?

Hint 2

Equal balances at two boundaries identify which interval?

Hint 3

Store the earliest boundary for each balance and maximize their distance.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Never replace the earliest matching boundary

[0,1,0,1,1,0]
6