Minimum Number of Operations to Make String Sorted — LeetCode 1830 Python Solution

HardMathStringCombinatorics
Problem
#1830
Reading time
5 min

The 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 i such that 1 <= i < s.length and s[i] < s[i - 1].

Example

Input
s = "cba"
Output
5
Explanation
The simulation goes as follows:

Python solution

Python
n = 3010
mod = 10**9 + 7
f = [1] + [0] * n
g = [1] + [0] * n

for i in range(1, n):
    f[i] = f[i - 1] * i % mod
    g[i] = pow(f[i], mod - 2, mod)


class Solution:
    def makeStringSorted(self, s: str) -> int:
        cnt = Counter(s)
        ans, n = 0, len(s)
        for i, c in enumerate(s):
            m = sum(v for a, v in cnt.items() if a < c)
            t = f[n - i - 1] * m
            for v in cnt.values():
                t = t * g[v] % mod
            ans = (ans + t) % mod
            cnt[c] -= 1
            if cnt[c] == 0:
                cnt.pop(c)
        return ans

Complexity

MeasureComplexity
TimeO(n \times k)
SpaceO(n) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1830. Minimum Number of Operations to Make String Sorted is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Combinatorics.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1830. Minimum Number of Operations to Make String Sorted?
LeetCode 1830. Minimum Number of Operations to Make String Sorted is rated Hard on LeetCode.
What is the time complexity of LeetCode 1830. Minimum Number of Operations to Make String Sorted?
The Python solution on this page runs in O(n \times k).
What is the space complexity of LeetCode 1830. Minimum Number of Operations to Make String Sorted?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1830. Minimum Number of Operations to Make String Sorted cover?
LeetCode 1830. Minimum Number of Operations to Make String Sorted is tagged Math, String and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview