Minimum Operations to Sort a String
You are given a string s consisting of lowercase English letters.
In a single operation, you can select any proper substring of s (a substring that is not the entire string itself) and sort its characters in non-descending alphabetical order.
Return the minimum number of operations required to completely sort the string s in non-descending alphabetical order. If it is impossible to sort the string, return -1.
Example 1:
Input: s = "bac"
Output: 1
Explanation:
Sort the substring "ba" to "ab". The string becomes "abc", which is sorted in ascending order. Thus, the answer is 1.
Example 2:
Input: s = "dcab"
Output: 2
Explanation:
Sort the substring "dca" to "acd", making s = "acdb".
Sort the substring "cdb" to "bcd", making s = "abcd", which is sorted. Thus, the answer is 2.
Now Your Turn!
Pick the correct output for the given inputInput: s = "zx"
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= s.length <= 105
- s consists solely of lowercase English letters.