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:
- 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
- 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.
- 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++
#include <bits/stdc++.h>
using namespace std;
string maximumPalinUsingKChanges(string str, int k)
{
string palin = str;
int l = 0;
int r = str.length() - 1;
while (l < r) {
if (str[l] != str[r]) {
palin[l] = palin[r] =
max(str[l], str[r]);
k--;
}
l++;
r--;
}
if (k < 0)
return "Not possible" ;
l = 0;
r = str.length() - 1;
while (l <= r) {
if (l == r) {
if (k > 0)
palin[l] = '9' ;
}
if (palin[l] < '9' ) {
if (k >= 2 && palin[l] == str[l]
&& palin[r] == str[r]) {
k -= 2;
palin[l] = palin[r] = '9' ;
}
else if (k >= 1
&& (palin[l] != str[l]
|| palin[r] != str[r])) {
k--;
palin[l] = palin[r] = '9' ;
}
}
l++;
r--;
}
return palin;
}
int main()
{
string str = "43435" ;
int k = 3;
cout << maximumPalinUsingKChanges(str, k);
return 0;
}
|
Java
import java.text.ParseException;
class GFG {
static String maximumPalinUsingKChanges(String str,
int k)
{
char palin[] = str.toCharArray();
String ans = "" ;
int l = 0 ;
int r = str.length() - 1 ;
while (l < r) {
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 < 0 ) {
return "Not possible" ;
}
l = 0 ;
r = str.length() - 1 ;
while (l <= r) {
if (l == r) {
if (k > 0 ) {
palin[l] = '9' ;
}
}
if (palin[l] < '9' ) {
if (k >= 2 && palin[l] == str.charAt(l)
&& palin[r] == str.charAt(r)) {
k -= 2 ;
palin[l] = palin[r] = '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;
}
public static void main(String[] args)
throws ParseException
{
String str = "43435" ;
int k = 3 ;
System.out.println(
maximumPalinUsingKChanges(str, k));
}
}
|
Python
def maximumPalinUsingKChanges(strr, k):
palin = strr[::]
l = 0
r = len (strr) - 1
while (l < = r):
if (strr[l] ! = strr[r]):
palin[l] = palin[r] =
max (strr[l], strr[r])
k - = 1
l + = 1
r - = 1
if (k < 0 ):
return "Not possible"
l = 0
r = len (strr) - 1
while (l < = r):
if (l = = r):
if (k > 0 ):
palin[l] = '9'
if (palin[l] < '9' ):
if (k > = 2 and palin[l] = = strr[l] and
palin[r] = = strr[r]):
k - = 2
palin[l] = palin[r] = '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
st = "43435"
strr = [i for i in st]
k = 3
a = maximumPalinUsingKChanges(strr, k)
print ("".join(a))
|
C#
using System;
public class GFG {
static String maximumPalinUsingKChanges(String str,
int k)
{
char [] palin = str.ToCharArray();
String ans = "" ;
int l = 0;
int r = str.Length - 1;
while (l < r) {
if (str[l] != str[r]) {
palin[l] = palin[r]
= ( char )Math.Max(str[l], str[r]);
k--;
}
l++;
r--;
}
if (k < 0) {
return "Not possible" ;
}
l = 0;
r = str.Length - 1;
while (l <= r) {
if (l == r) {
if (k > 0) {
palin[l] = '9' ;
}
}
if (palin[l] < '9' ) {
if (k >= 2 && palin[l] == str[l]
&& palin[r] == str[r]) {
k -= 2;
palin[l] = palin[r] = '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;
}
public static void Main()
{
String str = "43435" ;
int k = 3;
Console.Write(maximumPalinUsingKChanges(str, k));
}
}
|
Javascript
<script>
function maximumPalinUsingKChanges(str,k)
{
let palin = str.split( "" );
let ans = "" ;
let l = 0;
let r = str.length - 1;
while (l < r) {
if (str[l] != str[r]) {
palin[l] = palin[r] = String.fromCharCode(Math.max(
str.charAt(l), str.charAt(r)));
k--;
}
l++;
r--;
}
if (k < 0) {
return "Not possible" ;
}
l = 0;
r = str.length - 1;
while (l <= r) {
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 (let i = 0; i < palin.length; i++)
ans += palin[i];
return ans;
}
let str = "43435" ;
let k = 3;
document.write(maximumPalinUsingKChanges(str, k));
</script>
|
Time complexity: O(n)
Auxiliary Space: O(n) because it is using extra space for creating array and string
Approach 2: Using Greedy Algorithm
In this approach, we start by comparing the digits on the opposite ends of the given string. If they are equal, we move towards the center of the string. If they are not equal, we replace the smaller digit with the larger one to make the string a palindrome. We count the number of such replacements and stop when the number of replacements exceeds K or the string becomes a palindrome. If the number of replacements is less than K, we continue replacing digits with the largest ones until we reach the center of the string.
Here is the C++ code for this approach:
C++
#include <iostream>
#include <string>
using namespace std;
string makePalindrome(string s, int k) {
int n = s.length();
int replacements = 0;
for ( int i = 0, j = n - 1; i < j; i++, j--) {
if (s[i] != s[j]) {
if (s[i] > s[j]) {
s[j] = s[i];
} else {
s[i] = s[j];
}
replacements++;
if (replacements > k) {
return "-1" ;
}
}
}
for ( int i = 0, j = n - 1; i <= j; i++, j--) {
if (i == j && replacements < k) {
s[i] = '9' ;
}
if (s[i] != '9' ) {
if (replacements < k && (i == 0 || i == j)) {
s[i] = s[j] = '9' ;
replacements++;
} else if (replacements <= k - 2) {
s[i] = s[j] = '9' ;
replacements += 2;
}
}
}
return s;
}
int main() {
string s = "43435" ;
int k=3;
cout << makePalindrome(s, k) << endl;
return 0;
}
|
Java
import java.util.*;
class Main {
public static String makePalindrome(String s, int k) {
int n = s.length();
int replacements = 0 ;
char [] arr = s.toCharArray();
for ( int i = 0 , j = n - 1 ; i < j; i++, j--) {
if (arr[i] != arr[j]) {
if (arr[i] > arr[j]) {
arr[j] = arr[i];
} else {
arr[i] = arr[j];
}
replacements++;
if (replacements > k) {
return "-1" ;
}
}
}
for ( int i = 0 , j = n - 1 ; i <= j; i++, j--) {
if (i == j && replacements < k) {
arr[i] = '9' ;
}
if (arr[i] != '9' ) {
if (replacements < k && (i == 0 || i == j)) {
arr[i] = arr[j] = '9' ;
replacements++;
} else if (replacements <= k - 2 ) {
arr[i] = arr[j] = '9' ;
replacements += 2 ;
}
}
}
return new String(arr);
}
public static void main(String[] args) {
String s = "43435" ;
int k= 3 ;
System.out.println(makePalindrome(s, k));
}
}
|
Python3
def make_palindrome(s, k):
n = len (s)
replacements = 0
s = list (s)
for i in range (n / / 2 ):
j = n - i - 1
if s[i] ! = s[j]:
if s[i] > s[j]:
s[j] = s[i]
else :
s[i] = s[j]
replacements + = 1
if replacements > k:
return "-1"
for i in range (n / / 2 ):
j = n - i - 1
if s[i] ! = '9' :
if replacements < k and (i = = 0 or i = = j):
s[i] = s[j] = '9'
replacements + = 1
elif replacements < = k - 2 :
s[i] = s[j] = '9'
replacements + = 2
if n % 2 ! = 0 and replacements < k:
s[n / / 2 ] = '9'
return "".join(s)
S = "43435"
K = 3
print (make_palindrome(S, K))
|
C#
using System;
class GFG {
public static string MakePalindrome( string s, int k)
{
int n = s.Length;
int replacements = 0;
char [] arr = s.ToCharArray();
for ( int i = 0, j = n - 1; i < j; i++, j--) {
if (arr[i] != arr[j]) {
if (arr[i] > arr[j]) {
arr[j] = arr[i];
}
else {
arr[i] = arr[j];
}
replacements++;
if (replacements > k) {
return "-1" ;
}
}
}
for ( int i = 0, j = n - 1; i <= j; i++, j--) {
if (i == j && replacements < k) {
arr[i] = '9' ;
}
if (arr[i] != '9' ) {
if (replacements < k
&& (i == 0 || i == j)) {
arr[i] = arr[j] = '9' ;
replacements++;
}
else if (replacements <= k - 2) {
arr[i] = arr[j] = '9' ;
replacements += 2;
}
}
}
return new string (arr);
}
public static void Main( string [] args)
{
string s = "43435" ;
int k = 3;
Console.WriteLine(MakePalindrome(s, k));
}
}
|
Javascript
function makePalindrome(s, k) {
let n = s.length;
let replacements = 0;
for (let i = 0, j = n - 1; i < j; i++, j--) {
if (s[i] != s[j]) {
if (s[i] > s[j]) {
s = s.substring(0, j) + s[i] + s.substring(j + 1);
} else {
s = s.substring(0, i) + s[j] + s.substring(i + 1);
}
replacements++;
if (replacements > k) {
return "-1" ;
}
}
}
for (let i = 0, j = n - 1; i <= j; i++, j--) {
if (i == j && replacements < k) {
s = s.substring(0, i) + "9" + s.substring(i + 1);
}
if (s[i] != "9" ) {
if (replacements < k && (i == 0 || i == j)) {
s = s.substring(0, i) + "9" + s.substring(i + 1);
s = s.substring(0, j) + "9" + s.substring(j + 1);
replacements++;
} else if (replacements <= k - 2) {
s = s.substring(0, i) + "9" + s.substring(i + 1);
s = s.substring(0, j) + "9" + s.substring(j + 1);
replacements += 2;
}
}
}
return s;
}
let s = "43435" ;
let k = 3;
console.log(makePalindrome(s, k));
|
The time complexity of the first approach is O(N^2), where N is the length of the string, because we are using two nested loops to compare every pair of characters in the string.
The space complexity is O(N), because we are creating a new string of length N to store the modified palindrome.
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
06 Dec, 2023
Like Article
Save Article