Minimum Number of Operations to Make String Sorted

You are given a string s (0-indexed). You are asked to perform the following operation on s until you get a sorted string:

  • Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1].
  • Find the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the possible values of k in the range [i, j] inclusive.
  • Swap the two characters at indices i - 1 and j.
  • Reverse the suffix starting at index i.

Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 10^9 + 7.

Example 1
Inputs = "cba"
Output5
The operation sequence takes 5 steps to transform "cba" into the sorted string "abc".
Example 2
Inputs = "aabaa"
Output2
The operation sequence takes 2 steps to transform "aabaa" into the sorted string "aaaab".

Constraints

  • 1 <= s.length <= 3000
  • s consists only of 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