Editorial
For a binary string , consider the values defined in the constraints. Reading one character changes the value by exactly one.
For each (), define
The equality means that the -th step crosses the boundary between the integers and .
An interval contains equally many zeroes and ones exactly when . Applying an operation reverses only the order of the crossed boundaries inside this interval. Thus, it reverses and leaves all other values unchanged.
Therefore, for every integer , the number of crossings between and is invariant. Hence the following two multisets must be equal:
This condition is also sufficient. Regard as the current sequence and as the target sequence, and make them equal from left to right.
Assume the first positions already match. If , continue. Otherwise, the two edge levels describe the two opposite directions available from the current height. Since the current path first moves in the wrong direction, the first later crossing of the target edge leaves the current height toward the target side, and its second crossing returns to the current height.
Let be the position of the second occurrence of in the current suffix starting at . The original binary-string interval starts and ends at the same height, so it contains equally many zeroes and ones and is a valid operation interval.
The operation reverses . Since the last value is , the new value at position becomes correct.
When the invariant multisets are equal, the required second occurrence always exists. For every position, scan the remaining suffix linearly and reverse the selected segment directly. Each position costs time, so the total time complexity is . The memory complexity is .
At most one operation is produced for each position, so the total number of operations is at most .
Solution written by GPT5.6