Contiguous Array
Difficulty: Medium · Pattern: Prefix Sum · LeetCode #525
Given a binary array, return the maximum length of a contiguous subarray with an equal number of 0s and 1s.
Examples
text
[0, 1] → 2
[0, 1, 0] → 2
[0, 0, 1, 0, 1, 1] → 6Hints
- Replace each 0 with −1. Now you want the longest subarray with sum 0.
- A zero-sum subarray exists between two equal prefix sums.
Approach
Track a running sum (+1 for 1, −1 for 0) and a map from each prefix sum to the first index where it occurred (seed {0: −1}). If the current sum was seen at index j, then nums[j+1..i] is balanced, so update the best length with i − j. Store only the first occurrence, to maximize length.
Complexity
Time: O(n). Space: O(n).
Python solution
def findMaxLength(nums):
first = {0: -1}
s = best = 0
for i, x in enumerate(nums):
s += 1 if x == 1 else -1
if s in first:
best = max(best, i - first[s])
else:
first[s] = i
return bestJavaScript solution
function findMaxLength(nums) {
const first = new Map([[0, -1]]); let s = 0, best = 0;
for (let i = 0; i < nums.length; i++) {
s += nums[i] === 1 ? 1 : -1;
if (first.has(s)) best = Math.max(best, i - first.get(s)); else first.set(s, i);
}
return best;
}