- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

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

- Related Questions & Answers
- Minimum number of Appends needed to make a string palindrome in C++
- Program to find minimum number of characters to be added to make it palindrome in Python
- Minimum number of deletions to make a string palindrome in C++.
- Program to count number of minimum swaps required to make it palindrome in Python
- C++ program to count minimum number of operations needed to make number n to 1
- Program to count number of operations needed to make string as concatenation of same string twice in Python
- Program to find minimum number of operations to make string sorted in Python
- Program to check string is palindrome with lowercase characters or not in Python
- C++ program to find minimum how many operations needed to make number 0
- Python program to check if a given string is number Palindrome
- Program to count minimum deletions needed to make character frequencies unique in Python
- Program to find minimum number of rocketships needed for rescue in Python
- Program to find number of coins needed to make the changes in Python
- C++ program to find minimum number of punches are needed to make way to reach target
- Minimum number of letters needed to make a total of n in C++.

Advertisements