Skip to content

Commit 0c2bba4

Browse files
authored
Create minimum-number-of-operations-to-make-string-sorted.py
1 parent d58ca85 commit 0c2bba4

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Time: O(26 * n) = O(n)
2+
# Space: O(26) = O(1)
3+
4+
inv = [0, 1]
5+
6+
7+
class Solution(object):
8+
def makeStringSorted(self, s): # count of prev_permutation
9+
"""
10+
:type s: str
11+
:rtype: int
12+
"""
13+
14+
def inverse(n, m):
15+
i = len(inv)
16+
while len(inv) <= n: # lazy initialization
17+
inv.append(inv[m%i]*(m-m//i) % m) # https://cp-algorithms.com/algebra/module-inverse.html
18+
i += 1
19+
return inv[n]
20+
21+
MOD = 10**9+7
22+
count, result, comb_total = [0]*26, 0, 1
23+
for i in reversed(xrange(len(s))):
24+
num = ord(s[i])-ord('a')
25+
count[num] += 1
26+
comb_total = (comb_total*(len(s)-i))*inverse(count[num], MOD)
27+
result = (result + (comb_total*sum(count[:num]))*inverse(len(s)-i, MOD)) % MOD
28+
return result

0 commit comments

Comments
 (0)