Program to find how many updates required to make string half monotonous in Python


Suppose we have a lowercase string s whose length is even. We have to find the minimum number of characters that need to be updated such that one of the following three conditions is satisfied for all i, where 0 ≤ i < n/2 and j, n/2 ≤ j < n −

  • s[i] > s[j]
  • s[i] < s[j]
  • s[i] == s[j]

So, if the input is like s = "pppxxp", then the output will be 1 because if we change the last "p" to "x", then this can satisfy the condition s[i] < s[j]

To solve this, we will follow these steps −

  • n := size of s
  • left := a dictionary containing frequencies of each character from the left half of s
  • right := a dictionary containing frequencies of each character from the right half of s
  • ans := n
  • for each character pivot in lowercase English letters, do
    • ans := minimum of ans and (n - left[pivot] - right[pivot])
    • good := sum of all elements present in (left[c] for each c in left if c <= pivot )
    • good := good + sum of all elements present in right[c] for each c in right if c > pivot
    • ans := minimum of ans and (n - good)
    • good := sum of all elements present in left[c] for each c in left if c > pivot
    • good := good + sum of all elements present in right[c] for each c in right if c <= pivot
    • ans := minimum of ans and (n - good)
  • return ans

Example

Let us see the following implementation to get better understanding −

from collections import Counter
from string import ascii_lowercase
def solve(s):
   n = len(s)
   left = Counter(s[: n >> 1])
   right = Counter(s[n >> 1 :])

   ans = n
   for pivot in ascii_lowercase:
      ans = min(ans, n - left[pivot] - right[pivot])

      good = sum(left[c] for c in left if c <= pivot)
      good += sum(right[c] for c in right if c > pivot)
      ans = min(ans, n - good)

      good = sum(left[c] for c in left if c > pivot)
      good += sum(right[c] for c in right if c <= pivot)
      ans = min(ans, n - good)

   return ans

s = "pppxxp"
print(solve(s))

Input

"pppxxp"

Output

1

Updated on: 18-Oct-2021

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements