Editorial
For a string , define the following two values.
is the number of 0s at relative odd positions of minus the number of 0s at relative even positions.
is the number of 1s at relative odd positions of minus the number of 1s at relative even positions.
If a string is vanishing, then necessarily
When two equal adjacent characters are deleted, one of them is at an odd position of the current string and the other is at an even position. Therefore, the odd-position count and the even-position count of that character both decrease by one, so and do not change. Both values are for the empty string, proving necessity.
Conversely, if , then always vanishes. If is empty, this is trivial. If is nonempty and has no equal adjacent characters, then it must alternate as 0101 or 1010. In such a string, one character appears only at odd positions and the other only at even positions, so both and cannot be .
Thus, every nonempty such has two equal adjacent characters. Deleting them preserves and reduces the length by . Repeating this process eventually produces the empty string.
Hence, a substring is vanishing if and only if .
Now give position sign if is odd and sign if is even. Define the prefix state
where is the sum of these signs over all 0s in positions through , and is defined similarly for 1s.
For a substring , its relative position parity is either the same as the original parity or completely reversed, depending on the parity of . Reversing every sign does not change whether both values are zero.
Therefore,
is vanishing if and only if
Scan the string from left to right while counting how many times each prefix state has appeared. If the current state has already appeared times, then exactly new vanishing substrings end at the current position. Initially, the empty prefix state has appeared once.
Using a map gives time, while a hash map gives expected time. The memory complexity is .
The number of substrings is at most
Since , the answer always fits in a signed 64-bit integer.
Solution written by GPT5.6