VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-insertions-to-form-a-palindrome-with-permutations-allowed/

⇱ Minimum insertions to form a palindrome with permutations allowed - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum insertions to form a palindrome with permutations allowed

Last Updated : 6 Mar, 2025

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

[Expected Approach]Character Frequency Counting - O(n) Time and O(1) Space

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).


Output
2

[Alternate Approach] using Bit manipulation - O(n) Time and O(1) Space

Initialize a mask to 0 and toggle bits for each character based on its position in the alphabet. If the mask becomes 0, the string is already a palindrome (return 0). Otherwise, the minimum insertions required are the number of set bits in the mask minus one.


Output
2
Comment
Article Tags: