Find the longest contiguous subarray with the same number of 0s and 1s.
Given a binary array, return the length of the longest contiguous subarray that contains an equal number of 0s and 1s.
A subarray must be contiguous and non-empty. If no such subarray exists, return 0.
Input Format
- An integer array
numsconsisting only of0and1. - The array length is
n.
Output Format
- Return a single integer: the maximum length of a contiguous subarray with equal numbers of
0and1.
Constraints
nums[i] \in {0, 1}- Return
0if no balanced subarray exists.
Example 1
Input
nums = [0,1]
Output
2
Explanation
The whole array has one 0 and one 1, so the longest balanced subarray has length 2.
Example 2
Input
nums = [0,1,0]
Output
2
Explanation
The subarrays [0,1] and [1,0] are balanced, both with length 2.
Show 1 more example
Example 3
Input
nums = [0,0,1,0,0,0,1,1]
Output
6
Explanation
One longest balanced subarray is [0,1,0,0,0,1] after transforming 0 to -1 and finding a repeated prefix sum distance of 6.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.