
- 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 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
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
- Related Articles
- Program to check minimum number of characters needed to make string palindrome in Python
- Program to count number of minimum swaps required to make it palindrome in Python
- Minimum number of Parentheses to be added to make it valid in C++
- Program to find minimum number of characters to be deleted to make A's before B's in Python
- Program to find minimum number of operations to make string sorted in Python
- Find minimum number of merge operations to make an array palindrome in C++
- Program to find minimum number of days to wait to make profit in python
- Program to find minimum number of operations required to make one number to another in Python
- Program to find minimum number of days to make m bouquets using Python
- Minimum number of deletions to make a string palindrome in C++.
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Minimum number of Appends needed to make a string palindrome in C++
- Print the arranged positions of characters to make palindrome in C Program.
- Program to find minimum number of heights to be increased to reach destination in Python
- What least number must be added to 81180 to make it a perfect square?

Advertisements