Problem 336
Longest Balanced Binary Substring
Medium · 20 pts · String, Hash Table, Prefix Sum
Problem
A binary string contains only the characters 0 and 1. Find the length of the longest contiguous substring that contains equally many 0s and 1s. The 0s and 1s do not need to be grouped together; only their counts matter. If there is no such substring, print 0. Treat 0 as -1 and 1 as +1: the task becomes finding the longest substring with sum 0.
Input
A single binary string S.
Output
Print the length of the longest balanced substring.
Constraints
1 <= |S| <= 100000
Example input
1101000
Example output
6
Explanation
In '1101000' the first six characters '110100' contain three 1s and three 0s, so they form a balanced substring of length 6. The whole string has three 1s and four 0s, so nothing longer is balanced.