Minimum removal of characters required such that permutation of given string is a palindrome

• Last Updated : 14 Jun, 2021

Given string str consisting of lowercase letters, the task is to find the minimum number of characters to be deleted from the given string such that any permutation of the remaining string is a palindrome.

Examples:

Input: str=”aba”
Output: 1
Explanation: Removing ‘b’ generates a palindromic string “aa”.

Input: “abab”
Output: 0
Explanation: Permutations “abba”, “baab” of the given string are already palindrome. Therefore, no character needs to be deleted.

Input: “abab”
Output: 0

Approach: Follow the steps below to solve the problem:

1. Check if the given string is already a palindrome or not. If found to be true, print 0.
2. Otherwise, calculate the frequency of each character in the string using a Hashmap.
3. Count the number of characters with odd frequencies and store it in a variable, say k.
4. Now, the total number of characters required to be deleted is k-1. Therefore, print k – 1 as the required answer.

Below is the implementation of the above approach:

C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to check if a string``// is palindrome or not``bool` `IsPalindrome(string& str)``{``    ``string s = str;` `    ``// Reverse the string``    ``reverse(str.begin(), str.end());` `    ``// Check if the string is``    ``// already a palindrome or not``    ``if` `(s == str) {` `        ``return` `true``;``    ``}` `    ``return` `false``;``}` `// Function to calculate the minimum``// deletions to make a string palindrome``void` `CountDeletions(string& str, ``int` `len)``{``    ``if` `(IsPalindrome(str)) {` `        ``cout << 0 << endl;``        ``return``;``    ``}` `    ``// Stores the frequencies``    ``// of each character``    ``map<``char``, ``int``> mp;` `    ``// Iterate over the string``    ``for` `(``int` `i = 0; i < len; i++) {` `        ``// Update frequency of``        ``// each character``        ``mp[str[i]]++;``    ``}` `    ``int` `k = 0;` `    ``// Iterate over the map``    ``for` `(``auto` `it : mp) {` `        ``// Count characters with``        ``// odd frequencies``        ``if` `(it.second & 1) {``            ``k++;``        ``}``    ``}` `    ``// Print the result``    ``cout << k - 1 << endl;``}` `int` `main()``{``    ``string str = ``"abca"``;``    ``int` `len = str.length();``    ``CountDeletions(str, len);``}`

Java

 `// Java program for the``// above approach``import` `java.util.*;``class` `GFG{``  ` `static` `String str;` `static` `String reverse(String input)``{``  ``char``[] a = input.toCharArray();``  ``int` `l, r = a.length - ``1``;``  ` `  ``for` `(l = ``0``; l < r; l++, r--)``  ``{``    ``char` `temp = a[l];``    ``a[l] = a[r];``    ``a[r] = temp;``  ``}``  ``return` `String.valueOf(a);``}``  ` `// Function to check if a String``// is palindrome or not``static` `boolean` `IsPalindrome()``{``  ``String s = str;` `  ``// Reverse the String``  ``s = reverse(str);` `  ``// Check if the String is``  ``// already a palindrome or not``  ``if` `(s == str)``  ``{``    ``return` `true``;``  ``}` `  ``return` `false``;``}` `// Function to calculate the``// minimum deletions to make``// a String palindrome``static` `void` `CountDeletions(``int` `len)``{``  ``if` `(IsPalindrome())``  ``{``    ``System.out.print(``0` `+ ``"\n"``);``    ``return``;``  ``}` `  ``// Stores the frequencies``  ``// of each character``  ``HashMap mp =``          ``new` `HashMap<>();` `  ``// Iterate over the String``  ``for` `(``int` `i = ``0``; i < len; i++)``  ``{``    ``// Update frequency of``    ``// each character``    ``if``(mp.containsKey(str.charAt(i)))``    ``{``      ``mp.put(str.charAt(i),``      ``mp.get(str.charAt(i)) + ``1``);``    ``}``    ``else``    ``{``      ``mp.put(str.charAt(i), ``1``);``    ``}``  ``}` `  ``int` `k = ``0``;` `  ``// Iterate over the map``  ``for` `(Map.Entry it :``       ``mp.entrySet())``  ``{``    ``// Count characters with``    ``// odd frequencies``    ``if` `(it.getValue() % ``2` `== ``1``)``    ``{``      ``k++;``    ``}``  ``}` `  ``// Print the result``  ``System.out.print(k - ``1` `+ ``"\n"``);``}` `// Driver code``public` `static` `void` `main(String[] args)``{``  ``str = ``"abca"``;``  ``int` `len = str.length();``  ``CountDeletions(len);``}``}` `// This code is contributed by gauravrajput1`

Python3

 `# Python3 program for the above approach``from` `collections ``import` `defaultdict` `# Function to check if a string``# is palindrome or not``def` `IsPalindrome(``str``):``    ` `    ``s ``=` `str` `    ``# Reverse the string``    ``s ``=` `s[::``-``1``]` `    ``# Check if the string is``    ``# already a palindrome or not``    ``if` `(s ``=``=` `str``):``        ``return` `True` `    ``return` `False` `# Function to calculate the minimum``# deletions to make a string palindrome``def` `CountDeletions(``str``, ln):` `    ``if` `(IsPalindrome(``str``)):``        ``print``(``0``)``        ``return` `    ``# Stores the frequencies``    ``# of each character``    ``mp ``=` `defaultdict(``lambda` `: ``0``)` `    ``# Iterate over the string``    ``for` `i ``in` `range``(ln):``        ` `        ``# Update frequency of``        ``# each character``        ``mp[``str``[i]] ``+``=` `1` `    ``k ``=` `0` `    ``# Iterate over the map``    ``for` `it ``in` `mp.keys():``        ` `        ``# Count characters with``        ``# odd frequencies``        ``if` `(mp[it] & ``1``):``            ``k ``+``=` `1` `    ``# Print the result``    ``print``(k ``-` `1``)` `# Driver code``if` `__name__ ``=``=` `'__main__'``:` `    ``str` `=` `"abca"` `    ``ln ``=` `len``(``str``)` `    ``# Function Call``    ``CountDeletions(``str``, ln)` `# This code is contributed by Shivam Singh`

C#

 `// C# program for the``// above approach``using` `System;``using` `System.Collections.Generic;``class` `GFG{``  ` `static` `String str;` `static` `String reverse(String input)``{``  ``char``[] a = input.ToCharArray();``  ``int` `l, r = a.Length - 1;``  ` `  ``for` `(l = 0; l < r; l++, r--)``  ``{``    ``char` `temp = a[l];``    ``a[l] = a[r];``    ``a[r] = temp;``  ``}``  ``return` `String.Join(``""``, a);``}``  ` `// Function to check if``// a String is palindrome ``// or not``static` `bool` `IsPalindrome()``{``  ``String s = str;` `  ``// Reverse the String``  ``s = reverse(str);` `  ``// Check if the String``  ``// is already a palindrome``  ``// or not``  ``if` `(s == str)``  ``{``    ``return` `true``;``  ``}` `  ``return` `false``;``}` `// Function to calculate the``// minimum deletions to make``// a String palindrome``static` `void` `CountDeletions(``int` `len)``{``  ``if` `(IsPalindrome())``  ``{``    ``Console.Write(0 + ``"\n"``);``    ``return``;``  ``}` `  ``// Stores the frequencies``  ``// of each character``  ``Dictionary<``char``,``             ``int``> mp =``             ``new` `Dictionary<``char``,``                            ``int``>();` `  ``// Iterate over the String``  ``for` `(``int` `i = 0; i < len; i++)``  ``{``    ``// Update frequency of``    ``// each character``    ``if``(mp.ContainsKey(str[i]))``    ``{``      ``mp[str[i]] = mp[str[i]] + 1;``    ``}``    ``else``    ``{``      ``mp.Add(str[i], 1);``    ``}``  ``}` `  ``int` `k = 0;` `  ``// Iterate over the map``  ``foreach` `(KeyValuePair<``char``,``                        ``int``> it ``in` `mp)``  ``{``    ``// Count characters with``    ``// odd frequencies``    ``if` `(it.Value % 2 == 1)``    ``{``      ``k++;``    ``}``  ``}` `  ``// Print the result``  ``Console.Write(k - 1 + ``"\n"``);``}` `// Driver code``public` `static` `void` `Main(String[] args)``{``  ``str = ``"abca"``;``  ``int` `len = str.Length;``  ``CountDeletions(len);``}``}` `// This code is contributed by Princi Singh`

Javascript

 ``

Output:

`1`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up