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 < length of s and s[i] < s[i - 1].

  • Select largest index j such that i <= j < length of s and s[k] < s[i - 1] for all the possible values of k in the range [i, j] inclusive.

  • 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.

So, 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".

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

Example

Let us see the following implementation to get better understanding

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

s = "ppqpp"
print(solve(s))

Input

"ppqpp"

Output

2

Updated on: 08-Oct-2021

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements