Find the minimum number of preprocess moves required to make two strings equal in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings P and Q of same lengths with only lower case letters, we have to count the minimum number of pre-processing moves on string P are needed to make it equal to string Q after applying below operations −

  • Select any index i and swap characters pi and qi.

  • Select any index i and swap characters pi and pn – i – 1.

  • Select any index i and swap characters qi and qn – i – 1.

Note − The value of i in range (0 ≤ i < n)

In one move we can change a character in P with any other character of English alphabet.

So, if the input is like P = “pqprpqp”, Q = “qprpqpp”, then the output will be 4 as if we set P0 = ‘q’, P2 = ‘r’, P3 = ‘p’ and P4 = ‘q’ and P will be “qqrpqqp”. After that we can get equal strings by the following sequence of operations: swap(P1, Q1) and swap(P1, P5).

To solve this, we will follow these steps −

  • n := size of P

  • res := 0

  • for i in range 0 to n / 2, do

    • my_map := a new map

    • my_map[P[i]] := 1

    • if P[i] is same as P[n - i - 1], then

      • my_map[P[n - i - 1]] := my_map[P[n - i - 1]] + 1

    • if Q[i] is in my_map, then

      • my_map[Q[i]] := my_map[Q[i]] + 1

    • otherwise,

      • my_map[Q[i]] := 1

    • if Q[n - i - 1] is in my_map, then

      • my_map[Q[n - 1 - i]] := my_map[Q[n - 1 - i]] + 1

    • otherwise,

      • my_map[Q[n - 1 - i]] := 1

    • size := size of my_map

    • if size is same as 4, then

      • res := res + 2

    • otherwise when size is same as 3, then

      • res := res + 1 + (1 when (P[i] is same as P[n - i - 1]), otherwise 0)

    • otherwise when size is same as 2, then

      • res := res + my_map[P[i]] is not same as 2

  • if n mod 2 is same as 1 and P[n / 2] is not same as Q[n / 2], then

    • res := res + 1

  • return res

Example 

Let us see the following implementation to get better understanding −

 Live Demo

def count_preprocess(P, Q):
   n = len(P)
   res = 0
   for i in range(n // 2):
      my_map = dict()
      my_map[P[i]] = 1
      if P[i] == P[n - i - 1]:
         my_map[P[n - i - 1]] += 1
      if Q[i] in my_map:
         my_map[Q[i]] += 1
      else:
         my_map[Q[i]] = 1
      if Q[n - i - 1] in my_map:
         my_map[Q[n - 1 - i]] += 1
      else:
         my_map[Q[n - 1 - i]] = 1
      size = len(my_map)
      if (size == 4):
         res += 2
      elif (size == 3):
         res += 1 + (P[i] == P[n - i - 1])
      elif (size == 2):
         res += my_map[P[i]] != 2
   if (n % 2 == 1 and P[n // 2] != Q[n // 2]):
      res += 1
   return res

A = "pqprpqp"
B = "qprpqpp"
print(count_preprocess(A, B))

Input

"pqprpqp", "qprpqpp"

Output

4
raja
Published on 20-Aug-2020 08:08:45
Advertisements