Contiguous Array (equal 0s and 1s)

Medium

Problem

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

Example 1

Input:  [0, 1, 0]
Output: 2

Example 2

Input:  [0, 0, 1, 0, 0, 0, 1, 1]
Output: 6

Test cases

Case 1

Input:    [0,1]
Expected: 2

Case 2

Input:    [0,1,0]
Expected: 2

Case 3

Input:    [0,0,1,0,0,0,1,1]
Expected: 6

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Treat 0 as −1, earliest prefix index

Time O(n)Space O(n)

With 0 → −1, equal counts mean a zero-sum subarray: the same running sum seen twice. Keep the earliest index for each sum to maximise length.

function findMaxLength(nums) {
const first = new Map([[0, -1]]);
let sum = 0, best = 0;
for (let i = 0; i < nums.length; i++) {
sum += nums[i] === 1 ? 1 : -1;
if (first.has(sum)) best = Math.max(best, i - first.get(sum));
else first.set(sum, i);
}
return best;
}