Program to find minimum number of characters to be added to make it palindrome in Python



Suppose we have a string s, we have to find the minimum number of characters to be inserted after s to make it a palindrome.

So, if the input is like s = "mad", then the output will be 2, as we can add "am" to make it "madam".

To solve this, we will follow these steps −

  • b := 256, m := 10^9 + 7

  • s := a list by taking the difference of (ASCII of i) − 97 for each i in s

  • r := last element of s, l := last element of s

  • n := size of s

  • res := n − 1

  • p := b

  • for i in range n − 2 to 0, decrease by 1, do

    • r := r + s[i] * p, r := r mod m

    • l := l * b, l := l + s[i]

    • l := l mod m

    • p := p * b, p := p mod m

    • if l is same as r, then

      • res := i

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      b = 256
      m = 10 ** 9 + 7
      s = list(ord(i) − 97 for i in s)
      r = l = s[−1]
      n = len(s)
      res = n − 1
      p = b
      for i in range(n − 2, −1, −1):
         r += s[i] * p
         r %= m
         l *= b
         l += s[i]
         l %= m
         p *= b
         p %= m
         if l == r:
            res = i
      return res
ob = Solution()
s = "mad"
print(ob.solve(s))

Input

"mad"

Output

2

Advertisements