Friday, December 27, 2024
Google search engine
HomeData Modelling & AIMinimum insertions to form a palindrome with permutations allowed

Minimum insertions to form a palindrome with permutations allowed

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 : neveropen
Output : 2
neveropen can be changed as:
neveropenroforskeeg
neveropenorfroskeeg
and many more

Input : aabbc
Output : 0
aabbc can be changed as:
abcba
bacab

Method 1: A palindromic string can have one odd character only when the length of the string is odd otherwise all characters occur an even number of times. So, we have to find characters that occur at odd times in a string.

The idea is to count the occurrence of each character in a string. As a palindromic string can have one character which occurs odd times, so the number of insertion will be one less than the count of characters that occur at odd times. And if the string is already palindrome, we do not need to add any character, so the result will be 0. 

Implementation:

C++




// CPP program to find minimum number
// of insertions to make a string
// palindrome
#include <bits/stdc++.h>
using namespace std;
  
// Function will return number of
// characters to be added
int minInsertion(string str)
{
    // To store string length
    int n = str.length();
  
    // To store number of characters
    // occurring odd number of times
    int res = 0;
  
    // To store count of each
    // character
    int count[26] = { 0 };
  
    // To store occurrence of each
    // character
    for (int i = 0; i < n; i++)
        count[str[i] - 'a']++;
  
    // To count characters with odd
    // occurrence
    for (int i = 0; i < 26; i++)
        if (count[i] % 2 == 1)
            res++;
  
    // As one character can be odd return
    // res - 1 but if string is already
    // palindrome return 0
    return (res == 0) ? 0 : res - 1;
}
  
// Driver program
int main()
{
    string str = "neveropen";
    cout << minInsertion(str);
  
    return 0;
}


Java




// Java program to find minimum number
// of insertions to make a string
// palindrome
public class Palindrome {
  
    // Function will return number of
    // characters to be added
    static int minInsertion(String str)
    {
        // To store string length
        int n = str.length();
  
        // To store number of characters
        // occurring odd number of times
        int res = 0;
  
        // To store count of each
        // character
        int[] count = new int[26];
  
        // To store occurrence of each
        // character
        for (int i = 0; i < n; i++)
            count[str.charAt(i) - 'a']++;
  
        // To count characters with odd
        // occurrence
        for (int i = 0; i < 26; i++) {
            if (count[i] % 2 == 1)
                res++;
        }
  
        // As one character can be odd return
        // res - 1 but if string is already
        // palindrome return 0
        return (res == 0) ? 0 : res - 1;
    }
  
    // Driver program
    public static void main(String[] args)
    {
        String str = "neveropen";
        System.out.println(minInsertion(str));
    }
}


Python3




# Python3 program to find minimum number
# of insertions to make a string
# palindrome
import math as mt
  
# Function will return number of
# characters to be added
def minInsertion(tr1):
  
    # To store string length
    n = len(str1)
  
    # To store number of characters
    # occurring odd number of times
    res = 0
  
    # To store count of each
    # character
    count = [0 for i in range(26)]
  
    # To store occurrence of each
    # character
    for i in range(n):
        count[ord(str1[i]) - ord('a')] += 1
  
    # To count characters with odd
    # occurrence
    for i in range(26):
        if (count[i] % 2 == 1):
            res += 1
  
    # As one character can be odd return
    # res - 1 but if string is already
    # palindrome return 0
    if (res == 0):
        return 0
    else:
        return res - 1
  
# Driver Code
str1 = "neveropen"
print(minInsertion(str1))
  
# This code is contributed by 
# Mohit kumar 29


C#




// C# program to find minimum number
// of insertions to make a string
// palindrome
using System;
  
public class GFG {
  
    // Function will return number of
    // characters to be added
    static int minInsertion(String str)
    {
          
        // To store string length
        int n = str.Length;
  
        // To store number of characters
        // occurring odd number of times
        int res = 0;
  
        // To store count of each
        // character
        int[] count = new int[26];
  
        // To store occurrence of each
        // character
        for (int i = 0; i < n; i++)
            count[str[i] - 'a']++;
  
        // To count characters with odd
        // occurrence
        for (int i = 0; i < 26; i++) {
            if (count[i] % 2 == 1)
                res++;
        }
  
        // As one character can be odd
        // return res - 1 but if string
        // is already palindrome
        // return 0
        return (res == 0) ? 0 : res - 1;
    }
  
    // Driver program
    public static void Main()
    {
        string str = "neveropen";
          
        Console.WriteLine(minInsertion(str));
    }
}
  
// This code is contributed by vt_m.


PHP




<?php
// PHP program to find minimum number
// of insertions to make a string
// palindrome
  
// Function will return number of
// characters to be added
function minInsertion($str)
{
    // To store string length
    $n = strlen($str);
  
    // To store number of characters
    // occurring odd number of times
    $res = 0;
  
    // To store count of each
    // character
    $count = array(26);
  
    // To store occurrence of each
    // character
    for ($i = 0; $i < $n; $i++)
        $count[ord($str[$i]) - ord('a')]++;
  
    // To count characters with odd
    // occurrence
    for ($i = 0; $i < 26; $i++)
    {
        if ($count[$i] % 2 == 1)
            $res++;
    }
  
    // As one character can be odd return
    // res - 1 but if string is already
    // palindrome return 0
    return ($res == 0) ? 0 : $res - 1;
}
  
// Driver program
$str = "neveropen";
echo(minInsertion($str));
  
// This code is contributed 
// by Mukul Singh
?>


Javascript




<script>
  
// JavaScript program to find minimum number
// of insertions to make a string
// palindrome
      
    // Function will return number of
    // characters to be added
    function minInsertion(str)
    {
        // To store string length
        let n = str.length;
    
        // To store number of characters
        // occurring odd number of times
        let res = 0;
    
        // To store count of each
        // character
        let count = new Array(26);
        for(let i=0;i<count.length;i++)
        {
            count[i]=0;
        }
    
        // To store occurrence of each
        // character
        for (let i = 0; i < n; i++)
            count[str[i].charCodeAt(0) - 
            'a'.charCodeAt(0)]++;
    
        // To count characters with odd
        // occurrence
        for (let i = 0; i < 26; i++) {
            if (count[i] % 2 == 1)
                res++;
        }
    
        // As one character can be odd return
        // res - 1 but if string is already
        // palindrome return 0
        return (res == 0) ? 0 : res - 1;
    }
      
    // Driver program
    let str = "neveropen";
    document.write(minInsertion(str));
      
  
// This code is contributed by unknown2108
  
</script>


Output

2

Time Complexity: O(n) 
Auxiliary Space: O(1)

Method 2: An approach using Bit manipulation:

  • Create a mask and initialise it to zero.
  • For each character in string str, toggle the bit into the mask with its corresponding position in the alphabet.
  • Check if mask is equal to zero, and return 0.
  • Otherwise, return number of setbit in mask – 1.

Below is the implementation of the above approach:

C++




// CPP program to find minimum number
// of insertions to make a string
// palindrome
#include <bits/stdc++.h>
using namespace std;
  
// Function will return number of
// characters to be added
int minInsertion(string str)
{
    long long mask = 0;
  
    for (auto c : str)
        mask ^= (1 << (c - 'a'));
  
    if (mask == 0)
        return 0;
    int count = 0;
  
    while (mask) {
        count += mask & 1;
        mask = mask >> 1;
    }
  
    return count - 1;
}
  
// Driver program
int main()
{
    string str = "neveropen";
    cout << minInsertion(str);
  
    return 0;
}
  
// This code is contributed by hkdass001


Java




// Java program to find minimum number
// of insertions to make a string
// palindrome
import java.util.*;
  
public class GFG {
  
    // Function will return number of
    // characters to be added
    static int minInsertion(String str)
    {
        long mask = 0;
  
        for (char c : str.toCharArray())
            mask ^= (1 << (c - 'a'));
  
        if (mask == 0)
            return 0;
        int count = 0;
  
        while (mask != 0) {
            count += mask & 1;
            mask = mask >> 1;
        }
  
        return count - 1;
    }
  
    // Driver program
    public static void main(String[] args)
    {
        String str = "neveropen";
        System.out.println(minInsertion(str));
    }
}
  
// This code is contributed by Karandeep1234


Python3




# Python program to find minimum number
# of insertions to make a string
# palindrome
  
# Function will return number of
# characters to be added
def minInsertion(str):
    mask = 0
  
    for c in str:
        mask ^= (1 << (ord(c) - ord('a')))
  
    if mask == 0:
        return 0
    count = 0
  
    while mask:
        count += mask & 1
        mask = mask >> 1
  
    return count - 1
  
str = "neveropen"
print(minInsertion(str))
  
# This code is contributed by ishankhandelwals.


C#




// C# program to find minimum number
// of insertions to make a string
// palindrome
using System;
using System.Collections.Generic;
  
class GFG
{
    
  // Function will return number of
  // characters to be added
  static int minInsertion(string str)
  {
    int mask = 0;
  
    foreach(char c in str)
      mask ^= (1 << (c - 'a'));
  
    if (mask == 0)
      return 0;
    int count = 0;
  
    while (mask>0) {
      count += mask & 1;
      mask = mask >> 1;
    }
  
    return count - 1;
  }
  
  // Driver program
  static void Main(string[] args)
  {
    string str = "neveropen";
    Console.Write(minInsertion(str));
  }
}
  
// This code is contributed by ratiagrawal.


Javascript




// JavaScript program to find minimum number of insertions to make a string palindrome
  
// Function will return number of characters to be added
function minInsertion(str) {
    let mask = 0;
  
    // loop through the string
    for (let c of str) {
        // XOR the ascii value of character with the mask
        mask ^= (1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)));
    }
  
    // return 0 if mask is 0
    if (mask === 0) {
        return 0;
    }
  
    let count = 0;
  
    // loop through the mask
    while (mask) {
        count += mask & 1;
        mask = mask >> 1;
    }
  
    // return the count minus 1
    return count - 1;
}
  
// Driver program
let str = "neveropen";
console.log(minInsertion(str));


Output

2

Time Complexity: O(n) 
Auxiliary Space: O(1)

This article is contributed by nuclode. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks. 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments