Minimum Number of Operations to Make String Sorted - Problem

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

  1. Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1].
  2. 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.
  3. Swap the two characters at indices i - 1 and j.
  4. 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 109 + 7.

Input & Output

Example 1 — Small String
$ Input: s = "cba"
Output: 5
💡 Note: The operations transform: "cba" → "cab" → "acb" → "abc". Total operations needed: 5
Example 2 — Already Sorted
$ Input: s = "aabbc"
Output: 0
💡 Note: String is already sorted, so no operations are needed
Example 3 — Reverse Order
$ Input: s = "dcba"
Output: 11
💡 Note: Worst case: completely reverse sorted string requires 11 operations to sort

Constraints

  • 1 ≤ s.length ≤ 3000
  • s consists only of lowercase English letters

Visualization

Tap to expand
Minimum Operations to Make String Sorted INPUT String s = "cba" c i=0 b i=1 a i=2 Target (sorted): "abc" a b c Total permutations of "abc": 3! = 6 "cba" is the 6th (last) "abc" is the 1st ALGORITHM STEPS 1 Count Permutations Use factorial formula 2 For each position Count smaller chars to right 3 Calculate contribution smaller * (n-i-1)! / dup! 4 Sum all contributions Rank = sum + 1 Calculation for "cba": i=0: 'c' has 2 smaller (a,b) 2 * 2! = 4 i=1: 'b' has 1 smaller (a) 1 * 1! = 1 Total rank: 4 + 1 = 5 FINAL RESULT Operations needed: 5 All 6 permutations: 1. abc (sorted) 2. acb 3. bac 4. bca 5. cab 6. cba (input) 6 - 1 = 5 ops OK mod 10^9+7 Key Insight: The number of operations equals the lexicographic rank of the string minus 1. Each operation is equivalent to finding the previous permutation. Use factorials and modular inverse to efficiently calculate how many permutations come before the input string. Time: O(n^2), Space: O(n) TutorialsPoint - Minimum Number of Operations to Make String Sorted | Optimal Solution
Asked in
Google 15 Amazon 8 Microsoft 5
12.0K Views
Medium Frequency
~45 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen