# Make largest palindrome by changing at most K-digits

• Difficulty Level : Medium
• Last Updated : 16 Jun, 2022

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.
Examples:

```Input   : str = “43435”
k = 3
Output  : "93939"
Explanation:
Lexicographically largest palindrome
after 3 changes is "93939"

Input :  str = “43435”
k = 1
Output : “53435”
Explanation:
Lexicographically largest palindrome
after 3 changes is “53435”

Input  : str = “12345”
k = 1
Output : "Not Possible"
Explanation:
It is not possible to make str palindrome
after 1 change.```

Approach:

1. 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. S
2. top 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.
3. 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:

## C++

 `// C++ program to get largest palindrome changing``// atmost K digits``#include ``using` `namespace` `std;` `// Returns maximum possible``// palindrome using k changes``string maximumPalinUsingKChanges(string str, ``int` `k)``{``    ``string palin = str;` `    ``// Initialize l and r by leftmost and``    ``// rightmost ends``    ``int` `l = 0;``    ``int` `r = str.length() - 1;` `    ``//  first try to make string palindrome``    ``while` `(l < r) {``      ` `        ``// Replace left and right character by``        ``// maximum of both``        ``if` `(str[l] != str[r]) {``            ``palin[l] = palin[r] =``                  ``max(str[l], str[r]);``            ``k--;``        ``}``        ``l++;``        ``r--;``    ``}` `    ``// If k is negative then we can't make``    ``// string palindrome``    ``if` `(k < 0)``        ``return` `"Not possible"``;` `    ``l = 0;``    ``r = str.length() - 1;` `    ``while` `(l <= r) {``      ` `        ``// At mid character, if K>0 then change``        ``// it to 9``        ``if` `(l == r) {``            ``if` `(k > 0)``                ``palin[l] = ``'9'``;``        ``}` `        ``// If character at lth (same as rth) is``        ``// less than 9``        ``if` `(palin[l] < ``'9'``) {``            ``/* If none of them is changed in the``               ``previous loop then subtract 2 from K``               ``and convert both to 9 */``            ``if` `(k >= 2 && palin[l] == str[l]``                ``&& palin[r] == str[r]) {``                ``k -= 2;``                ``palin[l] = palin[r] = ``'9'``;``            ``}` `            ``/*  If one of them is changed``                ``in the previous``                ``loop then subtract 1 from K``                ``(1 more is``                ``subtracted already) and make them 9  */``            ``else` `if` `(k >= 1``                     ``&& (palin[l] != str[l]``                         ``|| palin[r] != str[r])) {``                ``k--;``                ``palin[l] = palin[r] = ``'9'``;``            ``}``        ``}``        ``l++;``        ``r--;``    ``}` `    ``return` `palin;``}` `//  Driver code to test above methods``int` `main()``{``    ``string str = ``"43435"``;``    ``int` `k = 3;``    ``cout << maximumPalinUsingKChanges(str, k);``    ``return` `0;``}`

## Java

 `// Java program to get largest palindrome changing``// atmost K digits` `import` `java.text.ParseException;` `class` `GFG {` `  ``// Returns maximum possible``  ``// palindrome using k changes``  ``static` `String maximumPalinUsingKChanges(String str,``                                          ``int` `k)``  ``{``    ``char` `palin[] = str.toCharArray();``    ``String ans = ``""``;` `    ``// Initialize l and r by leftmost and``    ``// rightmost ends``    ``int` `l = ``0``;``    ``int` `r = str.length() - ``1``;` `    ``// First try to make String palindrome``    ``while` `(l < r) {` `      ``// Replace left and right character by``      ``// maximum of both``      ``if` `(str.charAt(l) != str.charAt(r)) {``        ``palin[l] = palin[r] = (``char``)Math.max(``          ``str.charAt(l), str.charAt(r));``        ``k--;``      ``}``      ``l++;``      ``r--;``    ``}` `    ``// If k is negative then we can't make``    ``// String palindrome``    ``if` `(k < ``0``) {``      ``return` `"Not possible"``;``    ``}` `    ``l = ``0``;``    ``r = str.length() - ``1``;` `    ``while` `(l <= r) {` `      ``// At mid character, if K>0 then change``      ``// it to 9``      ``if` `(l == r) {``        ``if` `(k > ``0``) {``          ``palin[l] = ``'9'``;``        ``}``      ``}` `      ``// If character at lth (same as rth) is``      ``// less than 9``      ``if` `(palin[l] < ``'9'``) {` `        ``/* If none of them is changed in the``            ``previous loop then subtract 2 from K``            ``and convert both to 9 */``        ``if` `(k >= ``2` `&& palin[l] == str.charAt(l)``            ``&& palin[r] == str.charAt(r)) {``          ``k -= ``2``;``          ``palin[l] = palin[r] = ``'9'``;``        ``}` `        ``/* If one of them is changed in the``        ``previous loop then subtract``        ``1 from K (1 more``        ``is subtracted already) and make them 9 */``        ``else` `if` `(k >= ``1``                 ``&& (palin[l] != str.charAt(l)``                     ``|| palin[r]``                     ``!= str.charAt(r))) {``          ``k--;``          ``palin[l] = palin[r] = ``'9'``;``        ``}``      ``}``      ``l++;``      ``r--;``    ``}``    ``for` `(``int` `i = ``0``; i < palin.length; i++)``      ``ans += palin[i];``    ``return` `ans;``  ``}` `  ``// Driver code to test above methods``  ``public` `static` `void` `main(String[] args)``    ``throws` `ParseException``  ``{``    ``String str = ``"43435"``;``    ``int` `k = ``3``;``    ``System.out.println(``      ``maximumPalinUsingKChanges(str, k));``  ``}``}``// This code is contributed by 29ajaykumar`

## C#

 `// C# program to get largest palindrome changing``// atmost K digits` `using` `System;``public` `class` `GFG {` `  ``// Returns maximum possible``  ``// palindrome using k changes``  ``static` `String maximumPalinUsingKChanges(String str,``                                          ``int` `k)``  ``{``    ``char``[] palin = str.ToCharArray();``    ``String ans = ``""``;``    ` `    ``// Initialize l and r by leftmost and``    ``// rightmost ends``    ``int` `l = 0;``    ``int` `r = str.Length - 1;` `    ``// First try to make String palindrome``    ``while` `(l < r) {``      ` `      ``// Replace left and right character by``      ``// maximum of both``      ``if` `(str[l] != str[r]) {``        ``palin[l] = palin[r]``          ``= (``char``)Math.Max(str[l], str[r]);``        ``k--;``      ``}``      ``l++;``      ``r--;``    ``}` `    ``// If k is negative then we can't make``    ``// String palindrome``    ``if` `(k < 0) {``      ``return` `"Not possible"``;``    ``}` `    ``l = 0;``    ``r = str.Length - 1;` `    ``while` `(l <= r) {``      ` `      ``// At mid character, if K>0 then change``      ``// it to 9``      ``if` `(l == r) {``        ``if` `(k > 0) {``          ``palin[l] = ``'9'``;``        ``}``      ``}` `      ``// If character at lth (same as rth) is``      ``// less than 9``      ``if` `(palin[l] < ``'9'``) {``        ` `        ``/* If none of them is changed in the``        ``previous loop then subtract 2 from K``        ``and convert both to 9 */``        ``if` `(k >= 2 && palin[l] == str[l]``            ``&& palin[r] == str[r]) {``          ``k -= 2;``          ``palin[l] = palin[r] = ``'9'``;``        ``}``        ` `        ``/* If one of them is changed in the``        ``previous loop then subtract 1 from K (1 more``        ``is subtracted already) and make them 9 */``        ``else` `if` `(k >= 1``                 ``&& (palin[l] != str[l]``                     ``|| palin[r] != str[r])) {``          ``k--;``          ``palin[l] = palin[r] = ``'9'``;``        ``}``      ``}``      ``l++;``      ``r--;``    ``}``    ``for` `(``int` `i = 0; i < palin.Length; i++)``      ``ans += palin[i];``    ``return` `ans;``  ``}` `  ``// Driver code to test above methods``  ``public` `static` `void` `Main()``  ``{``    ``String str = ``"43435"``;``    ``int` `k = 3;``    ``Console.Write(maximumPalinUsingKChanges(str, k));``  ``}``}``// This code is contributed by Rajput-Ji`

## Python

 `# Python3 program to get largest palindrome changing``# atmost K digits` `# Returns maximum possible``# palindrome using k changes``def` `maximumPalinUsingKChanges(strr, k):``    ``palin ``=` `strr[::]` `    ``# Initialize l and r by leftmost and``    ``# rightmost ends``    ``l ``=` `0``    ``r ``=` `len``(strr) ``-` `1` `    ``# first try to make palindrome``    ``while` `(l <``=` `r):` `        ``# Replace left and right character by``        ``# maximum of both``        ``if` `(strr[l] !``=` `strr[r]):``            ``palin[l] ``=` `palin[r] ``=``                   ``max``(strr[l], strr[r])` `            ``# print(strr[l],strr[r])``            ``k ``-``=` `1``        ``l ``+``=` `1``        ``r ``-``=` `1` `    ``# If k is negative then we can't make``    ``# palindrome``    ``if` `(k < ``0``):``        ``return` `"Not possible"` `    ``l ``=` `0``    ``r ``=` `len``(strr) ``-` `1` `    ``while` `(l <``=` `r):` `        ``# At mid character, if K>0 then change``        ``# it to 9``        ``if` `(l ``=``=` `r):``            ``if` `(k > ``0``):``                ``palin[l] ``=` `'9'` `        ``# If character at lth (same as rth) is``        ``# less than 9``        ``if` `(palin[l] < ``'9'``):` `            ``# If none of them is changed in the``            ``# previous loop then subtract 2 from K``            ``# and convert both to 9``            ``if` `(k >``=` `2` `and` `palin[l] ``=``=` `strr[l] ``and``                           ``palin[r] ``=``=` `strr[r]):``                ``k ``-``=` `2``                ``palin[l] ``=` `palin[r] ``=` `'9'` `            ``# If one of them is changed in the previous``            ``# loop then subtract 1 from K (1 more is``            ``# subtracted already) and make them 9``            ``elif` `(k >``=` `1` `and` `(palin[l] !``=` `strr[l] ``or``                              ``palin[r] !``=` `strr[r])):``                ``k ``-``=` `1``                ``palin[l] ``=` `palin[r] ``=` `'9'` `        ``l ``+``=` `1``        ``r ``-``=` `1` `    ``return` `palin`  `# Driver code``st ``=` `"43435"``strr ``=` `[i ``for` `i ``in` `st]``k ``=` `3``a ``=` `maximumPalinUsingKChanges(strr, k)``print``("".join(a))` `# This code is contributed by mohit kumar 29`

## Javascript

 ``

Output:

`93939`

Time complexity: O(n)

Auxiliary Space: O(1)

This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.

My Personal Notes arrow_drop_up