← ALL NOTES
String

3863. Minimum Operations to Sort a String

The answer is one of 0, 1, 2, 3 and -1, and the length of the string has nothing to do with which. Every proper substring lies inside the prefix s[0..n-2] or inside the suffix s[1..n-1], and widening a move to one of those two windows never costs anything: if sorting s[l..r] with r <= n-2 leaves the string sorted, the multiset is unchanged, so the global maximum must already be sitting at the last index, which is exactly the condition under which sorting the whole prefix also leaves it sorted. The same argument runs the other way for ranges that touch the end. Two moves, then, for a string of 10^5 characters.

Loading…