Minimum Number of Operations to Make String Sorted LeetCode solution in Python
1from math import gcd234class Solution:5def makeStringSorted(self, s: str) -> int:6s = [ord(c) - ord("a") for c in s]7ans, MOD = 0, 10**9 + 78cnt, t, d, step = [0] * 26, 1, 1, 19cnt[s[-1]] = 110for c in reversed(s[:-1]):11d *= cnt[c] + 112t *= step13g = gcd(d, t)14d //= g15t //= g16ans = (ans + t * sum(cnt[i] for i in range(c)) // d) % MOD17cnt[c] += 118step += 119return ans