The simplest approach is to check every possible subarray and count the number of zeros and ones in each. When we find a subarray where the count of zeros equals the count of ones, we have found a valid contiguous array. We keep track of the maximum length among all valid subarrays.
i from 0 to n-1.j from i to n-1.Instead of counting zeros and ones separately, we can treat zeros as -1 and ones as +1. When we compute a running sum, any subarray with equal zeros and ones will have a sum of 0. More importantly, if the running sum at index i equals the running sum at index j, then the subarray from i+1 to j has equal zeros and ones. We use an array to store the first occurrence of each possible running sum value.
diffIndex of size 2n+1 to store indices (the sum can range from -n to +n).0.+1 if it's 1, or -1 if it's 0.0, the entire subarray from the start to the current index is valid.class Solution:
def findMaxLength(self, nums: List[int]) -> int:
n = len(nums)
res = 0
diff_index = [None] * (2 * n + 1)
count = 0
for i in range(n):
count += 1 if nums[i] == 1 else -1
if count == 0:
res = i + 1
if diff_index[count + n] is not None:
res = max(res, i - diff_index[count + n])
else:
diff_index[count + n] = i
return resThis approach uses the same logic as the array solution but replaces the fixed-size array with a hash map. The key insight remains the same: if the difference between ones and zeros at two different indices is the same, the subarray between them contains equal zeros and ones. A hash map provides more flexibility and can be more memory-efficient when the array is sparse or when we want cleaner code.
ones - zeros) occurred.zeros equals ones, the entire prefix is valid, so update the result.class Solution:
def findMaxLength(self, nums: List[int]) -> int:
zero = one = res = 0
diff_index = {}
for i, n in enumerate(nums):
if n == 0:
zero += 1
else:
one += 1
if one - zero not in diff_index:
diff_index[one - zero] = i
if one == zero:
res = one + zero
else:
idx = diff_index[one - zero]
res = max(res, i - idx)
return resWhen the running sum (ones - zeros) becomes zero, the entire prefix from index 0 is valid. To handle this case uniformly, you must initialize the map with {0: -1} or handle it separately. Missing this causes incorrect results for subarrays starting at index 0.
# Wrong: No initialization for diff == 0
diff_index = {} # Misses subarrays starting from index 0
# Correct: Initialize with base case
diff_index = {0: -1} # or handle diff == 0 separatelyYou must check if the current difference already exists in the map BEFORE storing the current index. Storing first will overwrite the earlier index, and you want the earliest occurrence to maximize subarray length.
# Wrong: Store before check overwrites earlier index
diff_index[diff] = i
if diff in diff_index:
res = max(res, i - diff_index[diff]) # Always 0!
# Correct: Check first, then store only if new
if diff not in diff_index:
diff_index[diff] = iThe key insight is treating 0s as -1s so that equal counts yield a sum of 0. If you track ones and zeros separately without using this transformation, you cannot efficiently detect when a subarray has equal counts using the hash map approach.