Given a binary array nums containing only 0 and 1, return the maximum length of a contiguous subarray with an equal number of 0s and 1s.
Return 0 if no such subarray exists.
We use analytics and advertising cookies to understand how the site is used and whether our ads on Facebook and Instagram work. They are set only if you accept. See our Privacy Policy for details.
Given a binary array nums containing only 0 and 1, return the maximum length of a contiguous subarray with an equal number of 0s and 1s.
Return 0 if no such subarray exists.
A medium prefix sum problem, graded against 6 test cases (3 of them hidden).
Precomputed cumulative totals so any range query becomes one subtraction.
Reach for it when you see: Repeated range-sum queries, or counting subarrays that sum to a target.
More Prefix Sum problems →Counting two things at once is awkward. Map `0` to `-1` and `1` to `+1` and the condition collapses: a subarray has equal counts exactly when it sums to zero.
A subarray sums to zero when the running prefix has the same value at both ends. So sweep once, and the first time you see a prefix value, record its index; every later re-appearance of that value marks a balanced subarray, whose length is the index distance. Keeping only the first index for each value is what maximizes the length - a later occurrence would only ever produce a shorter span.
The seed `prefix 0 -> index -1` handles subarrays that start at index 0. Without it, `[0,1]` returns 0 instead of 2, which is the classic off-by-one in this problem.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.