Given a string S consisting of lowercase English alphabets, the task is to find the minimum number of characters required to be removed such that the characters of the string could be rearranged to form a palindrome.
Input: S = “ababccca”
Remove an occurrence of ‘c’ from the string. Therefore, the modified string is “ababcca”, which can be rearranged to form the palindromic string “cababac”.
Therefore, only one removal is required.
Input: S = abcde
Approach: The problem can be solved based on the observation that, in a palindromic string, at most one character can occur odd number of times. Therefore, reduce the frequency of all odd-frequent characters except one of them.
Follow the steps below to solve the problem:
- Initialize an array of size 26 for storing the frequency of each character in S.
- Traverse the string
- Update the frequency of each character in the frequency array.
- Count the number of characters having odd frequency and store it in a variable, say count.
- If count is 1 or 0, print 0 as the answer. Otherwise, print count – 1 as the answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.