Minimum operations to make a numeric string palindrome by removing at most 2 unique character occurrences
Given numeric string str, the task is to find the minimum operations needed to make the string palindrome. An operation is defined as:
- Select one character and remove any of its occurrences.
- For all the operations, the number of unique characters chosen must be less than 2
Input: str = “11221”
Explanation: Select ‘1’ and remove anyone character out of the first two characters of the given string. After the operation, the string becomes “1221” which is a palindrome.
Input: str = “1123211”
Explanation: The given string is already a palindrome.
Input: str = “1332”
Explanation: The string can’t be made palindrome after selecting a single character and removing the occurrences of the selected character only.
Approach: This problem can be solved with the help of the two-pointer approach.
Follow the steps below to solve the problem:
- Initialize a variable answer as n that stores our final answer (n is the length of the string).
- Iterate over ‘0’ to ‘9’ and let’s call it currentCharacter.
- Initialize toBeRemoved as 0. It stores the minimum number of characters to be removed of currentCharacter type from the string to make it a palindrome.
- Initialize i and j as 0 and n – 1 respectively.
- Initialize a possible as true. It helps us to determine whether it is possible to make the string palindrome by removing the occurrences of the character c only.
- Now run a nested while loop till i is less than j.
- Case 1: str[i] is equal to str[j], It means that we are not required to remove any character at the present step so we can increment i and decrement j.
- Case 2: str[i] is not equal to str[j] but str[i] is equal to currentCharacter. Increment i = i + 1 and toBeRemoved = toBeRemoved + 1 as we are removing this character.
- Case 3: str[i] is not equal to str[j] but str[j] is equal to currentCharacter. Increment j = j – 1 and toBeRemoved = toBeRemoved + 1 as we are removing this character
- Case 4: str[i] is not equal to str[j]. It means that we can’t make our string palindrome by removing the currentCharacter.
Below is the implementation of the above approach:
Time complexity: O(10 * n) = O(n) where n is the length of the string str.
Auxiliary Space: O(1)