Ctrl K

As Many Heads as Tails

Medium
A coin was flipped several times in a row and the results were written to the array flips: 1 for heads, 0 for tails. Find the longest contiguous run of flips with the same number of heads and tails, and return its length. If there is no such run, return 0.
Example 1
flips=[1, 1, 0, 1, 0, 0, 1, 1] → 6

The first six flips [1, 1, 0, 1, 0, 0] have three heads and three tails. No longer stretch is balanced.

Example 2
flips=[0, 0, 0] → 0

Only tails came up, so there is no balanced stretch and the answer is 0.

Example 3
flips=[1, 0, 0, 1] → 4
Constraints
  • 1 ≤ len(flips) ≤ 10⁵
  • flips[i] is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Run with a Given Sum MediumA Stretch Divisible by k MediumStretches With an Exact Total MediumWindows With an Exact Alarm Count MediumWindows With a Divisible Sum Medium
loading Python…
Input
flips=[1, 1, 0, 1, 0, 0, 1, 1]
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 114 tests on the server, hidden ones included.