Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find minimum number of operations to make string sorted in Python
Suppose we have a string s. We have to perform the following operation on s until we get a sorted string ?
Select largest index i such that 1 ? i
Select largest index j such that i ? j
Exchange two characters at indices i - 1 and j.
Reverse the suffix from index i.
We have to find the number of operations required to make the string sorted. The answer may be very large so return result modulo 10^9 + 7.
Example Walkthrough
If the input is like s = "ppqpp", then the output will be 2 because:
In first operation, i=3, j=4. Exchange s[2] and s[4] to get s="ppppq", then reverse the substring from index 3. Now, s="pppqp".
In second operation, i=4, j=4. Exchange s[3] and s[4] to get s="ppppq", then reverse the substring from index 4. Now, s="ppppq".
Algorithm Steps
To solve this, we will follow these steps ?
d := An array of size 26 and fill with 0
a := 0, t := 1
m := 10^9 + 7
n := ASCII of 'a'
-
For each index i and character c of s in reverse order, start index from 1, do:
j := ASCII of c - n
d[j] := d[j] + 1
a := (a + sum of all elements of d[from index 0 to j-1]) * quotient of t/d[j]) mod m
t := t * quotient of i/d[j]
Return a
Implementation
def solve(s):
d = [0] * 26
a = 0
t = 1
m = 10**9 + 7
n = ord('a')
for i, c in enumerate(s[::-1], 1):
j = ord(c) - n
d[j] += 1
a = (a + sum(d[:j]) * t // d[j]) % m
t = t * i // d[j]
return a
# Test the function
s = "ppqpp"
result = solve(s)
print(f"Number of operations needed: {result}")
Number of operations needed: 2
How It Works
This algorithm uses a mathematical approach based on the factorial number system. The key insights are:
We process the string in reverse order to count permutations efficiently
Array
dkeeps track of character frequencies seen so farVariable
aaccumulates the total operations neededVariable
trepresents the current factorial divisor
Conclusion
This algorithm efficiently calculates the minimum operations to sort a string by leveraging combinatorial mathematics. The time complexity is O(n) where n is the string length, making it optimal for this problem.
