Problem
Given a binary array nums
, return the maximum length of a contiguous subarray with an equal number of0
and1
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= nums.length <= 10^5
nums[i]
is either0
or1
.
Solution
Method 1 - Using Prefix Sum
To solve this problem, we use a hash map to store a prefix sum and its corresponding index. The key idea is to transform the problem into finding subarrays where the sum of elements is zero after mapping 0
to -1
. For each element in the array, calculate the running difference (prefix sum
) between the number of 1
s and 0
s. If this difference has been seen before, the subarray between the previous index and the current index has an equal number of 0
s and 1
s.
Approach
- Transform the Array: Map
0
to-1
while traversing. This makes finding an equal number of0
s and1
s equivalent to finding a subarray with a sum of 0. - Use Hash Map: Store
prefix_sum
as keys and their first occurrence index as values. If the sameprefix_sum
appears again later, the subarray between these indices has a sum of zero, indicating an equal number of0
s and1
s. - Iterate Over
nums
: Use the hash map to check if the current prefix sum was seen earlier. Calculate the length of the subarray (current index - previous index) and update the maximum length (ans
).
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
as we traverse the array once and perform constant-time operations for each element (hash map lookup and update). - 🧺 Space complexity:
O(n)
as we store prefix sums in a hash map, which in the worst case could grow to the size of the input array.