Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check minimum number of characters needed to make string palindrome in Python
A palindrome is a string that reads the same forwards and backwards. To make any string a palindrome, we need to find the minimum number of characters to insert. This can be solved using dynamic programming by comparing characters from both ends.
Problem Statement
Given a string, find the minimum number of characters needed to be inserted to make it a palindrome ?
For example, if the input is s = "mad", we can insert "am" to get "madam", requiring 2 insertions.
Algorithm
The approach uses a recursive function dp(i, j) that compares characters at positions i and j ?
If
i >= j, return 0 (base case)If
s[i] == s[j], move inward:dp(i + 1, j - 1)Otherwise, try both options and take minimum:
min(dp(i + 1, j), dp(i, j - 1)) + 1
Implementation
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)
# Test the solution
ob = Solution()
s = "mad"
result = ob.solve(s)
print(f"Minimum insertions needed for '{s}': {result}")
Minimum insertions needed for 'mad': 2
How It Works
For the string "mad" ?
Compare 'm' and 'd': they don't match
Try both possibilities: skip 'm' or skip 'd'
Recursively solve subproblems until base case
Return minimum insertions needed
Additional Examples
ob = Solution()
# Test multiple strings
test_cases = ["abc", "aab", "abcd", "racecar"]
for s in test_cases:
result = ob.solve(s)
print(f"'{s}' needs {result} insertions")
'abc' needs 2 insertions 'aab' needs 1 insertions 'abcd' needs 3 insertions 'racecar' needs 0 insertions
Conclusion
This dynamic programming solution efficiently finds the minimum character insertions needed to create a palindrome. The recursive approach compares characters from both ends and explores all possibilities to find the optimal solution.
