Skip to content
Onsite

Contiguous Array

MediumP2Coding

Given a binary array nums (every element is 0 or 1), return the length of the longest contiguous subarray that contains the same number of 0s and 1s. If there is none, return 0.

Example 1

Input
nums = [0,1]
Output
2
Why
[0,1] is the longest balanced subarray.

Example 2

Input
nums = [0,1,0]
Output
2
Why
Either [0,1] or [1,0], both of length 2.

Example 3

Input
nums = [0,0,1,0,0,0,1,1]
Output
6

Constraints

  • 0 <= nums.length <= 10^5
  • nums[i] is 0 or 1

Hints

Run checks the 3 visible tests, Submit all 10.