Minimum Number of Operations to Make String Sorted - Problem
You're given a string s and need to determine how many operations it takes to sort it using a specific algorithm. Think of this as reverse-engineering the next permutation algorithm!

The algorithm works like this:
1. Find the rightmost position where a character is smaller than its predecessor
2. Find the smallest character to the right that's still larger than the predecessor
3. Swap these two characters
4. Reverse everything after the swap position

Instead of actually performing these operations (which would be too slow), you need to calculate how many steps it would take using combinatorial mathematics. The key insight is that this is equivalent to finding the rank of the current permutation in lexicographic order!

Goal: Return the number of operations needed, modulo 109 + 7.

Input & Output

example_1.py โ€” Basic Example
$ Input: s = "cba"
โ€บ Output: 5
๐Ÿ’ก Note: The string "cba" needs to be sorted to "abc". Following the algorithm: cba โ†’ cab โ†’ bca โ†’ bac โ†’ acb โ†’ abc. This takes 5 operations total.
example_2.py โ€” With Duplicates
$ Input: s = "aabaa"
โ€บ Output: 2
๐Ÿ’ก Note: The string "aabaa" becomes sorted as "aaaab" in 2 operations. The presence of duplicate characters reduces the number of distinct permutations.
example_3.py โ€” Already Sorted
$ Input: s = "abc"
โ€บ Output: 0
๐Ÿ’ก Note: The string "abc" is already in sorted order, so no operations are needed. The algorithm detects this immediately.

Visualization

Tap to expand
Permutation Rank Calculation1Frequency CountCount occurrences of eachcharacter in the string2Factorial PrecomputationCalculate n! and modularinverses for efficiency3Rank CalculationFor each position, countsmaller arrangementsExample: "dcba"Position 0: 'd'Smaller chars: a,b,c (3 total)Arrangements: 3 ร— 3! = 18Position 1: 'c'Smaller chars: a,b (2 total)Arrangements: 2 ร— 2! = 4... continue for all positionsKey FormulaMultinomial Coefficient:n! / (nโ‚! ร— nโ‚‚! ร— ... ร— nโ‚–!)Total rank = sum of all smaller arrangements at each positionTime Complexity: O(nยฒ) | Space: O(n)
Understanding the Visualization
1
Setup Phase
Count character frequencies and precompute factorials with modular inverses
2
Position Analysis
For each position, count how many smaller characters appear later in the string
3
Permutation Counting
Calculate how many arrangements would start with those smaller characters
4
Duplicate Handling
Use multinomial coefficients to account for repeated characters
5
Accumulate Result
Sum all possibilities and update character frequencies for next position
Key Takeaway
๐ŸŽฏ Key Insight: Instead of simulating O(n!) operations, we mathematically calculate the permutation's lexicographic rank in O(nยฒ) time using combinatorial formulas.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

For each of n positions, we potentially check all remaining characters (26 max), plus factorial precomputation

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Space for factorial array, character frequencies, and input string

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค s.length โ‰ค 3000
  • s consists only of lowercase English letters
  • Result must be returned modulo 109 + 7
  • The string may contain duplicate characters
Asked in
Google 15 Amazon 12 Microsoft 8 ByteDance 6
28.4K Views
Medium Frequency
~35 min Avg. Time
847 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