Program to change minimum characters to satisfy one of three conditions in Python


Suppose we have two strings s and t with only lowercase letters. In one operation, we can change any character in s or t to any lowercase letter. We have to satisfy one of the following three conditions −

  • Every letter in s is strictly smaller than every letter in t in the alphabet.

  • Every letter in t is strictly smaller than every letter in s in the alphabet.

  • Both s and t consist of only one distinct letter.

We have to find the minimum number of operations required to get the result.

So, if the input is like s = "sts", t = "uss", then the output will be 2 because

  • If we change t to "uuu" in 2 operations, then every letter in s is less than every letter in t.

  • If we change s to "ttt" and t to "sss" in 3 operations, then every letter in t is less than every letter in s.

  • If we change s to "sss" and t to "sss" in 2 operations, then s and t consist of one distinct letter.

Here best way was done in 2 operations (either 1 or 3).

To solve this, we will follow these steps −

  • counter_s := map to hold frequency of each character in s
  • counter_t := map to hold frequency of each character in t
  • less_s := infinity, less_t := infinity, unique := infinity
  • accu_s := 0, accu_t := 0
  • for each character c in lowercase English character, do
    • unique := minimum of unique and (size of s + size of t - counter_s[c] - counter_t[c])
      • counter_t[c])
    • if ascii of c is greater than ascii of 'a', then
      • less_a := minimum of less_s and (size of s - accu_s + accu_t)
      • less_b := minimum of less_t and (size of t - accu_t + accu_s)
    • accu_s := accu_s + counter_s[c]
    • accu_t := accu_t + counter_t[c]
  • return minimum of less_s, less_t and unique

Example

Let us see the following implementation to get better understanding −

from collections import Counter
import string
def solve(s, t):
   counter_s = Counter(s)
   counter_t = Counter(t)
   less_s, less_t, unique = float('inf'), float('inf'), float('inf')
   accu_s, accu_t = 0, 0
   for c in string.ascii_lowercase:
      unique = min(unique, len(s) + len(t) - counter_s[c] - counter_t[c])
      if c > 'a':
         less_a = min(less_s, len(s) - accu_s + accu_t)
         less_b = min(less_t, len(t) - accu_t + accu_s)
      accu_s += counter_s[c]
      accu_t += counter_t[c]
   return min(less_s, less_t, unique)

s = "sts"
t = "uss"
print(solve(s, t))

Input

"sts", "uss"

Output

2

Updated on: 07-Oct-2021

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements