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 Sort StringInput String"cba"UnsortedApply Operations1. Find pivot index2. Find swap target3. Swap & reverse suffixOperations Count5ResultTransformation sequence: "cba" → "cab" → "bac" → "bca" → "abc"Mathematical approach avoids simulation and calculates directlyKey Challenge: Large strings can have up to 10^9 + 7 operationsSolution: Use factorial number system and modular arithmeticTime: O(n²) | Space: O(n)
Understanding the Visualization
1
Input
Unsorted string like "cba"
2
Operations
Apply the 4-step operation repeatedly
3
Output
Count of operations needed (5 for "cba")
Key Takeaway
🎯 Key Insight: The operations are reverse next-permutation - use factorial number system to calculate directly instead of simulating
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