Contiguous Array

Medium#525subarray sum

You get an array of 0s and 1s. Find the length of the longest contiguous subarray with as many 0s as 1s. Our example: [0, 1, 1, 0, 1, 1, 1, 0, 0] — the answer is 6: [0, 1, 1, 1, 0, 0] from index 3 to 8.

input
nums: an array of 0s and 1s.
returns
The length of the longest contiguous subarray with as many 0s as 1s; 0 if there is none.
constraints
  • 1 ≤ nums.length ≤ 10⁴
  • nums[i] is 0 or 1
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @return {number}
 */
function findMaxLength(nums) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more prefix sums problems

Pattern “Prefix sums” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.