An oscilloscope records a diagnostic trace as a string of pulse readings, where each character is either 0 (a low reading) or 1 (a high reading). A contiguous segment of the trace is called balanced if it consists of some number of consecutive low readings immediately followed by exactly that same number of consecutive high readings, with nothing else inside the segment (for example, 000111 is balanced, but 0011 1 with a stray extra 1, or 0101, or 1100, are not).
Given the trace, find the length (number of characters) of the longest balanced segment it contains. If the trace contains no balanced segment at all, output 0.
A single line containing the trace: a string of length between 1 and 10^5, made up only of the characters 0 and 1.
Print a single integer: the length of the longest balanced segment, or 0 if none exists.
0 and 1.Example 1
Input
00110
Expected
4
Explanation
The trace has a run of two '0's followed by a run of two '1's (positions 1-4, "0011"), giving a balanced segment of length 4. The trailing '0' cannot extend it, so 4 is the longest balanced segment.
Example 2
Input
110100
Expected
2
Explanation
Scanning run boundaries: the leading "11" run is followed by a '0' run, which is not a 0-then-1 boundary. Next, the single '0' at position 3 is followed by the single '1' at position 4, a balanced segment of length 2. That '1' is then followed by a '0' run, again not a 0-then-1 boundary. The only balanced segment found has length 2, so that is the answer.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →