![]() |
VOOZH | about |
Given a string of lowercase letters. Find minimum characters to be inserted in the string so that it can become palindrome. We can change the positions of characters in the string.
Examples:
Input: geeksforgeeks
Output: 2
Explanation: geeksforgeeks can be changed as: geeksroforskeeg or geeksorfroskeeg and many more using two insertion.
Input: aabbc
Output: 0
Explanation: aabbc can be changed as: abcba or bacab without any insertion
Table of Content
To make a string palindromic, count the occurrences of each character. A palindrome can have at most one character with an odd frequency; the rest must occur an even number of times. The minimum insertions required are one less than the count of characters with odd frequencies. If the string is already a palindrome, no insertions are needed (result = 0).
2
Initialize a mask to
0and toggle bits for each character based on its position in the alphabet. If the mask becomes0, the string is already a palindrome (return 0). Otherwise, the minimum insertions required are the number of set bits in the mask minus one.
2