Program to check minimum number of characters needed to make string palindrome in Python


Suppose we have a string s, we have to find the minimum number of characters needed to be inserted so that the string becomes a palindrome.

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

To solve this, we will follow these steps −

  • Define a function dp(). This will take i, j

  • if i >= j, then

    • return 0

  • if s[i] is same as s[j], then

    • return dp(i + 1, j - 1)

  • otherwise,

    • return minimum of dp(i + 1, j) and dp(i, j - 1) + 1

  • From the main method, do the following

  • return dp(0, size of s - 1)

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      def dp(i, j):
         if i >= j:
            return 0
         if s[i] == s[j]:
            return dp(i + 1, j - 1)
         else:
            return min(dp(i + 1, j), dp(i, j - 1)) + 1
      return dp(0, len(s) - 1)
ob = Solution()
s = "mad"
print(ob.solve(s))

Input

s = "mad"

Output

2

Updated on: 12-Oct-2020

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements