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:
- Find the largest index
isuch that1 <= i < s.lengthands[i] < s[i - 1]. - Find the largest index
jsuch thati <= j < s.lengthands[k] < s[i - 1]for all the possible values ofkin the range[i, j]inclusive. - Swap the two characters at indices
i - 1andj. - 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code