Practice

Contiguous Array

Module 12 · Prefix Sum

Problem

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

Examples

Example 1

Inputnums = [0,1]Output2

Explanation. the whole array

Example 2

Inputnums = [0,1,0]Output2

Explanation. [0,1] or [1,0]

Example 3

Inputnums = [0,0,1,0,1,1]Output6

Explanation. the whole array: three 0s, three 1s

Constraints

1 ≤ n ≤ 10⁵.

Attempt it first

The reduction move: this doesn't look like a prefix-sum problem at first glance ("equal 0s and 1s" isn't obviously a sum), but a one-line transformation turns it into exactly Subarray Sum Equals K's shape. Find the transformation before opening the hint.