Official

A - atcoder < S Editorial by evima


First of all, the answer is \(0\) if \(S\) > atcoder already holds at the beginning. Also, the answer is \(-1\) if \(S\) consists of a.

We will consider the remaining cases. Let the \(k\)-th character of \(S\) be the leftmost character in \(S\) that is not a. We can first see that the answer is \(k-1\) or \(k-2\). With \(k-3\) or fewer operations, the first two characters in \(S\) will still be aa, which means \(S<\)atcoder. On the other hand, with \(k-1\) operations, we can move \(S_k\) to the beginning of \(S\), making \(S>\)atcoder.

The only case in which \(k-2\) operations make \(S>\)atcoder is when we move \(S_k\) to the second position in \(S\). Thus, we can try doing it and check if it makes \(S>\)atcoder to see whether the answer is \(k-1\) or \(k-2\). More analysis also reveals that the answer is \(k-1\) if \(S_k\leq\)t and \(k-2\) otherwise. The time complexity of these solutions is \(O(|S|)\).

posted:
last update: