- 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 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 Questions & Answers
- Minimum number of Parentheses to be added to make it valid in C++
- 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
- Program to find minimum number of characters to be deleted to make A's before B's in Python
- Find minimum number of merge operations to make an array palindrome in C++
- Program to find minimum number of operations to make string sorted in Python
- 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 heights to be increased to reach destination in Python
- Minimum number of Appends needed to make a string palindrome in C++
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Print the arranged positions of characters to make palindrome in C Program.
- Find minimum number to be divided to make a number a perfect square in C++

Advertisements