Description
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Example 1:
Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
Example 2:
Input: nums = [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Constraints:
1 <= nums.length <= 10^5
nums[i] is either 0 or 1.
Solution
Prefix sum, use the difference between the count of 1
s and 0
s as the key, and the first index as the value. If two differences are the same, then all the subarray in between is a valid subarray.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
n
)
o(n)
o(n)
Code
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
prefix_sum = {0: -1}
cur_sum = 0
res = 0
for i, each_num in enumerate(nums):
cur_sum += (1 if each_num == 1 else -1)
res = max(res, i - prefix_sum.get(cur_sum, i))
prefix_sum[cur_sum] = prefix_sum.get(cur_sum, i)
return res