Contiguous Array Problem
Description
LeetCode Problem 525.
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
Approach: Prefix Balance with a Hash Map
Checking every subarray takes O(n2) time. Instead, turn the question into one about prefix sums.
Count each 1 as +1 and each 0 as -1, and keep a running balance. A subarray has as many 0s as 1s exactly when its values sum to 0, which means the balance is the same at both ends: if the balance after index j equals the balance after index i, then nums[j+1..i] is balanced, and its length is i - j.
So for each balance we only need the first index where it appeared, since the earliest one gives the longest subarray:
- Start with
firstIndex = {0: -1}: before reading anything the balance is 0. This lets a balanced prefix such as[0, 1]count with lengthi - (-1) = i + 1. - For each index
i, updatebalance. - If
balancewas seen before atj, update the answer withi - j. Otherwise recordfirstIndex[balance] = i.
Do not overwrite an index that is already stored: a later index would only give shorter subarrays.
Complexity: O(n) time and O(n) space, where n is the length of nums.
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
first_index = {0: -1} # balance -> first index where it appeared
balance = 0 # (number of 1s) - (number of 0s) so far
best = 0
for i, num in enumerate(nums):
balance += 1 if num == 1 else -1
if balance in first_index:
# Same balance as at first_index[balance]: the part in between is balanced.
best = max(best, i - first_index[balance])
else:
first_index[balance] = i
return best