Contiguous Array

Medium Prefix Sum

nums is a list of 0s and 1s.

A subarray is a stretch of nums in one piece, of one number or more. It is balanced when it holds as many 0s as 1s.

Return the length of the longest balanced subarray, or 0 if there is none.

Example 1

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

The first six numbers, 1 1 0 1 0 0, hold three 0s and three 1s. No longer stretch is balanced: a balanced stretch has an even length, and the whole list holds five 1s and three 0s.

Example 2

Input: nums = [1,1,1,0]
Output: 2

Example 3

Input: nums = [0,0,0]
Output: 0

Constraints

  • 1 ≤ nums.length ≤ 2 × 10⁵
  • nums[i] is 0 or 1

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

Watch the explanation

More Prefix Sum

All Prefix Sum problems