iq.lab
Python starts when a code cell comes near or you run one
mediumPrefix sumsHash maps and sets target 25 min

Longest balanced run

A list bits holds only 0s and 1s. Return the length of the longest subarray (a run of one or more neighboring items, with nothing skipped) that holds as many 0s as 1s. If no such run exists, return 0.

Example 1
Inputbits = [1, 1, 0, 1, 0, 0, 1, 1]Output6

Positions 0 to 5 hold three 1s and three 0s. Positions 1 to 6 and 2 to 7 work too. The whole list has five 1s and three 0s.

Example 2
Inputbits = [1, 0, 1, 1, 1]Output2

[1, 0] at positions 0 to 1, or [0, 1] at 1 to 2. Every longer run has more 1s than 0s.

Example 3
Inputbits = [1, 1, 1]Output0

There is no 0, so no run can balance.

Constraints
  • 1 ≤ len(bits) ≤ 105

  • Every item is 0 or 1.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.