
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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
- Program to check string is palindrome with lowercase characters or not in Python
- C++ program to count minimum number of operations needed to make number n to 1
- Program to find minimum number of operations to make string sorted in Python
- Program to count number of operations needed to make string as concatenation of same string twice in Python
- Python program to check if a given string is number Palindrome
- Program to count minimum deletions needed to make character frequencies unique in Python
- C++ program to find minimum how many operations needed to make number 0
- Program to find minimum number of rocketships needed for rescue in Python
- Minimum Insertion Steps to Make a String Palindrome in C++
- Program to find minimum operations needed to make two arrays sum equal in Python
- Program to find number of coins needed to make the changes in Python

Advertisements