Skip to content
BytePatterns

Longest Balanced Zeros and Ones

MediumHash Tables#prefix-sum#first-seen-index~20m

Problem

A log records each request as 1 for success and 0 for failure. Find the longest contiguous stretch of the log with exactly as many successes as failures, and return its length, or 0 if there is none. The log holds between 1 and 100,000 entries, so checking every stretch is too slow.

Examples

Input:  bits = [0, 1, 0]
Output: 2
Why:    [0, 1] and [1, 0] are both balanced; all three entries are not
Input:  bits = [0, 0, 1, 0, 0, 0, 1, 1]
Output: 6
Why:    the last six entries hold three of each
Input:  bits = [1, 1, 1]
Output: 0
Why:    edge case, no stretch is balanced

Hints

0 / 3

Stuck on the idea rather than the code? Subarray Sums With a Map covers it.