Contiguous Array

Given a binary array nums, return the maximum length of a contiguous subarray that contains an equal number of 0s and 1s.

30:00

Contiguous Array
medium
Free written solution
Topics
Companies

Given a binary array nums, return the maximum length of a contiguous subarray that contains an equal number of 0s and 1s.

Example 1:
Input: {"nums":[0,1]}
Output: 2
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • nums[i]\text{nums}[i] is either 00 or 11.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[0,1]}

Treat every 1 as a step up and every 0 as a step down. The walk starts at height 0 before index 0, so record height 0 at index -1.

the walk: 1 steps up, 0 steps down

-10

● first visit to a height

- - same height again = balanced run

▬ best run

nums

0
1

first index of each height

0 → -1
count = 0
best = 0
Variables
VariableValue
count0
best0
first[0]-1
DepthFunction Call
Stack empty
0/5