Given a string containing all digits, we need to convert this string to a palindrome by changing at most K digits. If many solutions are possible then print lexicographically largest one.
Input : str = “43435” k = 3 Output : "93939" Lexicographically largest palindrome after 3 changes is "93939" Input : str = “43435” k = 1 Output : “53435” Lexicographically largest palindrome after 3 changes is “53435” Input : str = “12345” k = 1 Output : "Not Possible" It is not possible to make str palindrome after 1 change.
We can solve this problem using two pointers method. We start from left and right and if both digits are not equal then we replace the smaller value with larger value and decrease k by 1. We stop when the left and right pointers cross each other, after they stop if value of k is negative, then it is not possible to make string palindrome using k changes. If k is positive, then we can further maximize the string by looping once again in the same manner from left and right and converting both the digits to 9 and decreasing k by 2. If k value remains to 1 and string length is odd then we make the middle character as 9 to maximize whole value.
Below is the implementation of above approach:
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Convert the string into palindrome string by changing only one character.
- Remove a character from a string to make it a palindrome
- Minimum removal to make palindrome permutation
- Make a lexicographically smallest palindrome with minimal changes
- Smallest and Largest Palindrome with N Digits
- Minimum number of deletions to make a string palindrome
- Print the arranged positions of characters to make palindrome
- Number of Counterclockwise shifts to make a string palindrome
- Minimum number of deletions to make a string palindrome | Set 2
- Make lexicographically smallest palindrome by substituting missing characters
- Minimum number of Appends needed to make a string palindrome
- Minimum number of characters to be replaced to make a given string Palindrome
- Minimum characters to be added at front to make string palindrome
- Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)
- Count all palindrome which is square of a palindrome