Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Contiguous Array
Problem
Given a binary array nums containing only 0s and 1s, return the length of the longest contiguous subarray that contains the same number of 0s as 1s. If no such subarray exists, return 0.
- The array is non-empty and has at most 200,000 elements.
- Every element is
0or1.
Examples
nums = [1, 0, 0, 1, 1, 0, 1]→6. The first six elements hold three 0s and three 1s; the whole array does not.nums = [1, 1, 0, 1]→2. Either[1,0]or[0,1]; nothing longer balances.nums = [0, 0, 0, 0]→0. No 1s at all, so no balanced subarray.
Hints
- "Equal number of 0s and 1s" is a statement about a count difference. Can you turn the array into something whose sum expresses that difference?
- Replace each 0 with -1. A subarray is balanced exactly when its sum is 0.
- A subarray sums to 0 when two prefix sums are equal. Remember where each prefix sum first appeared.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.