# 525. Contiguous Array
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
# Solution
Approach 1: use a hashtable to store differences of 0 and 1 seen so far.
# Code (Python)
Approach 1:
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
# Go through nums, record the diff of num 1s so far and num 0s so far.
# When diff1 == diff2, [diff1_index + 1, diff2_index] is a subarray.
table = {0: -1}
diff = 0
max_len = 0
for i, num in enumerate(nums):
if num == 1:
diff += 1
else:
diff -= 1
if diff in table:
max_len = max(max_len, i - table[diff])
else:
table[diff] = i
return max_len
# Code (C++)
Approach 1:
Approach 2: