Editor

Balanced Zeros and Ones

#153 · Lists · Advanced · 140 XP · about 25 min

bits is a list of 0s and 1s. Write longest_balanced(bits) that returns the length of the longest subarray (a stretch of neighbouring items) that contains as many 0s as 1s. Return 0 if there is none.

Examples

longest_balanced([0, 1])                    # returns 2
longest_balanced([0, 1, 0])                 # returns 2
longest_balanced([0, 0, 1, 0, 0, 0, 1, 1])  # returns 6
longest_balanced([1, 1, 1])                 # returns 0

In the third example the stretch [1, 0, 0, 0, 1, 1] (positions 2 to 7) has three of each.

Constraints

  • 0 <= len(bits) <= 100,000
  • Every item is 0 or 1

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.