Mid/SeniorString

Minimum Operations to Sort a String

You are given a string s consisting of lowercase English letters.

In one operation, you can select any substring of s that is not the entire string and sort it in non-descending alphabetical order.

Return the minimum number of operations required to make s sorted in non-descending order. If it is not possible, return -1.

Example 1
Inputs = "dog"
Output1
Sort substring "og" to "go", making s = "dgo", which is sorted in ascending order, so the answer is 1.
Example 2
Inputs = "card"
Output2
Sort substring "car" to "acr" to get s = "acrd", then sort substring "rd" to "dr", making s = "acdr", so the answer is 2.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of only lowercase English letters.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate