VOOZH about

URL: https://www.geeksforgeeks.org/dsa/make-largest-palindrome-changing-k-digits/

⇱ Make largest palindrome by changing at most K-digits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Make largest palindrome by changing at most K-digits

Last Updated : 11 May, 2025

You are given a string s consisting of digits (0-9) and an integer k. Convert the string into a palindrome by changing at most k digits. If multiple palindromes are possible, return the lexicographically largest one. If it's impossible to form a palindrome with k changes, return "Not Possible".

Examples: 

Input: s = “19495”, k = 3
Output: "99999"
Explanation: Lexicographically largest palindrome after 3 changes is "99999"

Input: s = “43436”, k = 1
Output: “63436”
Explanation: Lexicographically largest palindrome after 1 change is “63436”

Input: s = “11345”, k = 1
Output: "Not Possible"
Explanation: It is not possible to make s palindrome after 1 changes

[Approach 1] Using Two Pointers - O(n) time and O(n) space

  • 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.
  • 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.

Output
99999

Time complexity: O(n)
Auxiliary Space: O(n)

[Approach 2] Using Greedy Algorithm - O(n) time and O(1) space

In this approach, we greedily first count the required changes to make the string a palindrome by comparing characters from both ends. If the changes exceed k, return "Not Possible". Then, we traverse the string again to maximize it lexicographically by changing characters to '9' where possible, without exceeding the allowed k changes.


Output
99999

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

Comment
Article Tags: