Construct lexicographically smallest palindrome - GeeksforGeeks

29 Apr, 2021
Given a string of lowercase alphabets. Some of characters of given string got corrupted and are now represented by *. We can replace * with any of lowercase alphabets. You have to construct lexicographically smallest palindrome string. If it is not possible to construct a palindrome print “Not Possible”. Examples:  
Input : str[] = "bc*b" 
Output : bccb

Input : str[] = "bc*a*cb"
Output : bcaaacb

Input : str[] = "bac*cb"
Output : Not Possible
 
Start traversing the string from both end. Say with i=0, j=strlen-1, keep increasing i and decreasing j after every single iteration till i exceeds j. Now at any intermediate position we have five possible case :  
str[i] and str[j] both are same and also not equal to ‘*’. In this case simply continue.str[i] and str[j] both are same and are equal to ‘*’. Here you must fill str[i] = str[j] = ‘a’ for smallest possible palindrome.str[i] equals to ‘*’ and str[j] is some alphabet. Here fill str[i] = str[j] to make our string a palindrome.str[j] equals to ‘*’ and str[i] is some alphabet. Here fill str[j] = str[i] to make our string a palindrome.str[i] is not equals to str[j] and also both are some alphabet. In this case palindrome construction is not possible. So, print “Not Possible” and break from loop.
str[i] and str[j] both are same and also not equal to ‘*’. In this case simply continue.
str[i] and str[j] both are same and are equal to ‘*’. Here you must fill str[i] = str[j] = ‘a’ for smallest possible palindrome.
str[i] equals to ‘*’ and str[j] is some alphabet. Here fill str[i] = str[j] to make our string a palindrome.
str[j] equals to ‘*’ and str[i] is some alphabet. Here fill str[j] = str[i] to make our string a palindrome.
str[i] is not equals to str[j] and also both are some alphabet. In this case palindrome construction is not possible. So, print “Not Possible” and break from loop.
After i exceeds j means we have got our required palindrome. Else we got “Not possible” as result. 
C++
Java
Python3
C#
PHP
Javascript
// CPP for constructing smallest palindrome#include <bits/stdc++.h>using namespace std; // function for printing palindromestring constructPalin(string str, int len){    int i = 0, j = len - 1;     // iterate till i<j    for (; i < j; i++, j--) {         // continue if str[i]==str[j]        if (str[i] == str[j] && str[i] != '*')            continue;         // update str[i]=str[j]='a' if both are '*'        else if (str[i] == str[j] && str[i] == '*') {            str[i] = 'a';            str[j] = 'a';            continue;        }         // update str[i]=str[j] if only str[i]='*'        else if (str[i] == '*') {            str[i] = str[j];            continue;        }         // update str[j]=str[i] if only str[j]='*'        else if (str[j] == '*') {            str[j] = str[i];            continue;        }         // else print not possible and return        cout << "Not Possible";        return "";    }    return str;} // driver programint main(){    string str = "bca*xc**b";    int len = str.size();    cout << constructPalin(str, len);    return 0;}
// Java for constructing smallest palindromeclass GFG{ // function for printing palindromestatic String constructPalin(char []str, int len){    int i = 0, j = len - 1;     // iterate till i<j    for (; i < j; i++, j--)    {         // continue if str[i]==str[j]        if (str[i] == str[j] && str[i] != '*')            continue;         // update str[i]=str[j]='a' if both are '*'        else if (str[i] == str[j] &&                        str[i] == '*')        {            str[i] = 'a';            str[j] = 'a';            continue;        }         // update str[i]=str[j] if only str[i]='*'        else if (str[i] == '*')        {            str[i] = str[j];            continue;        }         // update str[j]=str[i] if only str[j]='*'        else if (str[j] == '*')        {            str[j] = str[i];            continue;        }         // else print not possible and return        System.out.println("Not Possible");        return "";    }    return String.valueOf(str);} // Driver codepublic static void main(String[] args){    String str = "bca*xc**b";    int len = str.length();    System.out.println(constructPalin(str.toCharArray(), len));}} // This code is contributed by 29AjayKumar
# Python3 for constructing smallest palindrome # function for printing palindromedef constructPalin(string, l):    string = list(string)    i = -1    j = l         # iterate till i<j    while i < j:        i += 1        j -= 1         # continue if str[i]==str[j]        if (string[i] == string[j] and            string[i] != '*'):            continue         # update str[i]=str[j]='a' if both are '*'        elif (string[i] == string[j] and              string[i] == '*'):            string[i] = 'a'            string[j] = 'a'            continue         # update str[i]=str[j] if only str[i]='*'        elif string[i] == '*':            string[i] = string[j]            continue         # update str[j]=str[i] if only str[j]='*'        elif string[j] == '*':            string[j] = string[i]            continue         # else print not possible and return        print("Not Possible")        return ""    return ''.join(string) # Driver Codeif __name__ == "__main__":    string = "bca*xc**b"    l = len(string)    print(constructPalin(string, l)) # This code is contributed by# sanjeev2552
// C# for constructing smallest palindromeusing System; class GFG{ // function for printing palindromestatic String constructPalin(char []str, int len){    int i = 0, j = len - 1;     // iterate till i<j    for (; i < j; i++, j--)    {         // continue if str[i]==str[j]        if (str[i] == str[j] && str[i] != '*')            continue;         // update str[i]=str[j]='a' if both are '*'        else if (str[i] == str[j] &&                        str[i] == '*')        {            str[i] = 'a';            str[j] = 'a';            continue;        }         // update str[i]=str[j] if only str[i]='*'        else if (str[i] == '*')        {            str[i] = str[j];            continue;        }         // update str[j]=str[i] if only str[j]='*'        else if (str[j] == '*')        {            str[j] = str[i];            continue;        }         // else print not possible and return        Console.WriteLine("Not Possible");        return "";    }    return String.Join("",str);} // Driver codepublic static void Main(String[] args){    String str = "bca*xc**b";    int len = str.Length;    Console.WriteLine(constructPalin(str.ToCharArray(), len));}} // This code contributed by Rajput-Ji
<?php// PHP for constructing smallest palindrome // function for printing palindromefunction constructPalin($str, $len){    $i = 0;    $j = $len - 1;     // iterate till i<j    for (; $i < $j; $i++, $j--)    {         // continue if str[i]==str[j]        if ($str[$i] == $str[$j] &&            $str[$i] != '*')            continue;         // update str[i]=str[j]='a' if both are '*'        else if ($str[$i] == $str[$j] &&                 $str[$i] == '*')        {            $str[$i] = 'a';            $str[$j] = 'a';            continue;        }         // update str[i]=str[j] if only str[i]='*'        else if ($str[$i] == '*')        {            $str[$i] = $str[$j];            continue;        }         // update str[j]=str[i] if only str[j]='*'        else if ($str[$j] == '*')        {            $str[$j] = $str[$i];            continue;        }         // else print not possible and return        echo "Not Possible";        return "";    }    return $str;} // Driver Code$str = "bca*xc**b";$len = strlen($str);echo constructPalin($str, $len); // This code is contributed by ita_c?>
<script> // javascript for constructing smallest palindrome // function for printing palindromefunction constructPalin(str, len){    var i = 0, j = len - 1;     // iterate till i<j    for (; i < j; i++, j--) {         // continue if str[i]==str[j]        if (str[i] == str[j] && str[i] != '*')            continue;         // update str[i]=str[j]='a' if both are '*'        else if (str[i] == str[j] && str[i] == '*') {            str[i] = 'a';            str[j] = 'a';            continue;        }         // update str[i]=str[j] if only str[i]='*'        else if (str[i] == '*') {            str[i] = str[j];            continue;        }         // update str[j]=str[i] if only str[j]='*'        else if (str[j] == '*') {            str[j] = str[i];            continue;        }         // else print not possible and return        document.write( "Not Possible");        return "";    }    return str.join("");} // driver programvar str = "bca*xc**b".split("");var len = str.length;document.write( constructPalin(str, len)); </script>
Output:  
bcacxcacb
 
ukasp
29AjayKumar
Rajput-Ji
sanjeev2552
noob2000
lexicographic-ordering
palindrome
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews