Python coding

Longest run with equal 0s and 1s

Given a list bits that contains only 0s and 1s, return the length of the longest contiguous run that holds exactly as many 0s as 1s. Return 0 if there is no such run.

bits may be empty. Aim for one pass.

Besides the tests, one large input (5,000 bits) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • longest_balanced([0,1]) → 2
  • longest_balanced([0,1,0]) → 2
  • longest_balanced([1,1,1,0,0,1,1,1]) → 4
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Treat each 0 as −1 and each 1 as +1. A run is balanced exactly when its sum is 0.

Hint 2

A run sums to 0 when the running total is the same before and after it. Store the first index where each total appears, and measure the distance when it shows up again.

Hint 3

Two traps: seed the map with total 0 at index −1, or runs that start at index 0 are missed; and never overwrite a stored index, because the earliest one gives the longest run.

Solution and why it works
pythonO(n) · O(n)
def longest_balanced(bits: list[int]) -> int:
    first_seen = {0: -1}                 # a total of 0 exists before the first bit
    total = best = 0
    for i, bit in enumerate(bits):
        total += 1 if bit else -1
        if total in first_seen:
            best = max(best, i - first_seen[total])
        else:
            first_seen[total] = i        # keep only the earliest index
    return best

Scoring 1 as +1 and 0 as −1 turns "equal counts" into "sum is 0", and a run sums to 0 exactly when the running total repeats. Keeping the first index of each total finds, in one pass, the farthest earlier point with the same total. Seed {0: -1} so runs that start at index 0 count, and never overwrite an index: a later one only shortens the run. Computing 2 * min(zeros, ones) is wrong: those bits need not be contiguous.