Skip to content

Contiguous Array

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

InputOutputSubarray
[0,1]2[0,1]
[0,1,0]2[0,1] or [1,0]
  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1
ApproachTimeSpaceNotes
Prefix Sum with 0→-1 TransformO(n)O(n)Optimal solution, single pass

* n = length of the input array

The problem asks for equal counts of 0 and 1. Directly comparing counts requires tracking two separate running totals. The insight is to collapse that into a single value:

Replace 0 with -1. Now each 1 contributes +1 and each 0 contributes -1. A subarray with equal 0s and 1s has net sum 0.

This reduces the problem to: find the longest subarray with sum 0, which is solved in O(n) with a prefix sum hash map — the same pattern as Subarray Sum Equals K.

The map stores the first index where each prefix sum was seen. When the same prefix sum reappears at index i, the subarray from seen[prefix]+1 to i has sum 0, so its length is i - seen[prefix]. We never update the map for a seen prefix — we always want the earliest occurrence to maximize window length.

Approach: Prefix Sum with 0→-1 Transform

Section titled “Approach: Prefix Sum with 0→-1 Transform”
★ Recommended
⏱ Time O(n) Single pass 💾 Space O(n) Hash map storage

Input: nums = [0,1,0,1]

After replacing 0→-1: [-1, 1, -1, 1]

inumdeltaprefixseen (before)length if matchbest
0&#123;&#125;0
00-1-1&#123;0:-1&#125;0
11+10&#123;0:-1, -1:0&#125;1−(−1)=22
20-1-1&#123;0:-1, -1:0&#125;2−0=22
31+10&#123;0:-1, -1:0&#125;3−(−1)=44

Result: 4

Input: nums = [0,1,0]

After replacing 0→-1: [-1, 1, -1]

ideltaprefixseen (before)length if matchbest
0&#123;&#125;0
0-1-1&#123;0:-1&#125;0
1+10&#123;0:-1, -1:0&#125;1−(−1)=22
2-1-1&#123;0:-1, -1:0&#125;2−0=22

Result: 2

Animated walkthrough

Finding maximum balanced subarray with prefix sums

Use Next or Autoplay to watch the prefix sum (with 0→-1) accumulate, the map record first-seen positions, and the window lengths calculate for nums=[0,1,0,1].

Step 1 of 5
Waiting to begin...
Array state
Memory / lookup state

function findMaxLength(nums):
seen = {0: -1}
prefix = 0
best = 0
for i, num in enumerate(nums):
prefix += 1 if num == 1 else -1
if prefix in seen:
best = max(best, i - seen[prefix])
else:
seen[prefix] = i
return best
contiguous_array_prefix_sum.py
from typing import List
def find_max_length(nums: List[int]) -> int:
seen = {0: -1}
prefix = 0
best = 0
for i, num in enumerate(nums):
prefix += 1 if num == 1 else -1
if prefix in seen:
best = max(best, i - seen[prefix])
else:
seen[prefix] = i
return best
print(find_max_length([0, 1])) # 2
print(find_max_length([0, 1, 0])) # 2
print(find_max_length([0, 1, 0, 1])) # 4