Skip to content
RED SAGSkills
medium30 ptsprefix-sumhash-map

Longest Balanced Bit Stretch

Given an array bits of 0s and 1s, return the length of the longest contiguous subarray containing equally many 0s and 1s. Return 0 if there is none.

Example 1

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

Example 2

Input: bits = [0, 1, 1, 0, 1, 1, 1, 0]
Output: 4
Explanation: The first four bits hold two 0s and two 1s.

Constraints

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

Count a 1 as +1 and a 0 as -1; a balanced stretch has total 0.

Hint 2

Remember the first index where each running balance appears.

Good practice for: Embedded Systems Engineer, Game Developer, Backend Developer, Blockchain Developer, Data Engineer

Run checks your code on 2 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.