The Wayback Machine - https://web.archive.org/web/20240708034338/https://www.geeksforgeeks.org/smallest-palindrome-replacement/
Open In App

Smallest Palindrome after replacement

Last Updated : 06 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string which has some lowercase alphabet characters and one special character dot(.). We need to replace all dots with some alphabet character in such a way that resultant string becomes a palindrome, in case of many possible replacements, we need to choose palindrome string which is lexicographically smallest. If it is not possible to convert string into palindrome after all possible replacements then output Not possible. 

Examples: 

Input : str = “ab..e.c.a”
Output : abcaeacba
The smallest palindrome which can be made 
after replacement is "abcaeacba"
We replaced first dot with "c", second dot with
"a", third dot with "a" and fourth dot with "b"

Input  : str = “ab..e.c.b”
Output : Not Possible 
It is not possible to convert above string into
palindrome

We can solve this problem as follows, As resultant string need to be palindrome, we can check pair of non-dot characters in starting itself, if they don’t match then direct return not possible because we can place new character at position of dots only not anywhere else. 

After that, we iterate over characters of string, if current character is dot, then we check its paired character (character at (n – i -1)th position), if that character is also dot, then we can replace both character by ‘a’, because ‘a’ is smallest lowercase alphabet which will guarantee smallest lexicographic string at the end, replacing both by any other character will result in lexicographically larger palindromic string. In other case, if paired character is not a dot, then to make string palindrome we must replace current character by its paired character. 

So in short,
If both "i", and "n- i- 1" are dot, replace them by ‘a’
If one of them is a dot character replace that by other non-dot character

Above procedure gives us lexicographically smallest palindrome string. 

Implementation:

C++




// C++ program to get lexicographically smallest
// palindrome string
#include <bits/stdc++.h>
using namespace std;
 
// Utility method to check str is possible palindrome
// after ignoring .
bool isPossiblePalindrome(string str)
{
    int n = str.length();
    for (int i=0; i<n/2; i++)
    {
        /* If both left and right character are not
           dot and they are not equal also, then it
           is not possible to make this string a
           palindrome   */
        if (str[i] != '.' &&
            str[n-i-1] != '.' &&
            str[i] != str[n-i-1])
            return false;
    }
 
    return true;
}
 
// Returns lexicographically smallest palindrom
// string, if possible
string smallestPalindrome(string str)
{
    if (!isPossiblePalindrome(str))
        return "Not Possible";
 
    int n = str.length();
 
    //  loop through character of string
    for (int i = 0; i < n; i++)
    {
        if (str[i] == '.')
        {
            // if one of character is dot, replace dot
            // with other character
            if (str[n - i - 1] != '.')
                str[i] = str[n - i - 1];
 
            // if both character are dot, then replace
            // them with smallest character 'a'
            else
                str[i] = str[n - i - 1] = 'a';
        }
    }
 
    //  return the result
    return str;
}
 
//  Driver code to test above methods
int main()
{
    string str = "ab..e.c.a";
    cout << smallestPalindrome(str) << endl;
    return 0;
}


Java




// Java program to get lexicographically
// smallest palindrome string
class GFG
{
// Utility method to check str is
// possible palindrome after ignoring
static boolean isPossiblePalindrome(char str[])
{
int n = str.length;
for (int i = 0; i < n / 2; i++)
{
    /* If both left and right character
        are not dot and they are not
        equal also, then it is not
        possible to make this string a
        palindrome */
    if (str[i] != '.' &&
        str[n - i - 1] != '.' &&
        str[i] != str[n - i - 1])
        return false;
}
 
return true;
}
 
// Returns lexicographically smallest
// palindrome string, if possible
static void smallestPalindrome(char str[])
{
if (!isPossiblePalindrome(str))
    System.out.println("Not Possible");
 
int n = str.length;
 
// loop through character of string
for (int i = 0; i < n; i++)
{
    if (str[i] == '.')
    {
        // if one of character is dot,
        // replace dot with other character
        if (str[n - i - 1] != '.')
            str[i] = str[n - i - 1];
 
        // if both character are dot,
        // then replace them with
        // smallest character 'a'
        else
            str[i] = str[n - i - 1] = 'a';
    }
}
 
// return the result
for(int i = 0; i < n; i++)
    System.out.print(str[i] + "");
}
 
// Driver code
public static void main(String[] args)
{
    String str = "ab..e.c.a";
    char[] s = str.toCharArray();
    smallestPalindrome(s);
}
}
 
// This code is contributed
// by ChitraNayal


Python 3




# Python 3 program to get lexicographically
# smallest palindrome string
 
# Utility method to check str is
# possible palindrome after ignoring
def isPossiblePalindrome(str):
    n = len(str)
    for i in range(n // 2):
         
        # If both left and right character
        # are not dot and they are not
        # equal also, then it is not possible
        # to make this string a palindrome
        if (str[i] != '.' and
            str[n - i - 1] != '.' and
            str[i] != str[n - i - 1]):
            return False
 
    return True
 
# Returns lexicographically smallest
# palindrome string, if possible
def smallestPalindrome(str):
    if (not isPossiblePalindrome(str)):
        return "Not Possible"
 
    n = len(str)
    str = list(str)
     
    # loop through character of string
    for i in range(n):
        if (str[i] == '.'):
             
            # if one of character is dot,
            # replace dot with other character
            if (str[n - i - 1] != '.'):
                str[i] = str[n - i - 1]
 
            # if both character are dot,
            # then replace them with
            # smallest character 'a'
            else:
                str[i] = str[n - i - 1] = 'a'
 
    # return the result
    return str
 
# Driver code
if __name__ == "__main__":
    str = "ab..e.c.a"
    print(''.join(smallestPalindrome(str)))
 
# This code is contributed by ChitraNayal


C#




// C# program to get lexicographically
// smallest palindrome string
using System;
public class GFG
    {
    // Utility method to check str is
    // possible palindrome after ignoring
    static bool isPossiblePalindrome(char []str)
    {
    int n = str.Length;
    for (int i = 0; i < n / 2; i++)
    {
        /* If both left and right character
            are not dot and they are not
            equal also, then it is not
            possible to make this string a
            palindrome */
        if (str[i] != '.' &&
            str[n - i - 1] != '.' &&
            str[i] != str[n - i - 1])
            return false;
    }
 
    return true;
    }
 
    // Returns lexicographically smallest
    // palindrome string, if possible
    static void smallestPalindrome(char []str)
    {
    if (!isPossiblePalindrome(str))
        Console.WriteLine("Not Possible");
 
    int n = str.Length;
 
    // loop through character of string
    for (int i = 0; i < n; i++)
    {
        if (str[i] == '.')
        {
            // if one of character is dot,
            // replace dot with other character
            if (str[n - i - 1] != '.')
                str[i] = str[n - i - 1];
 
            // if both character are dot,
            // then replace them with
            // smallest character 'a'
            else
                str[i] = str[n - i - 1] = 'a';
        }
    }
 
    // return the result
    for(int i = 0; i < n; i++)
       Console.Write(str[i] + "");
    }
 
    // Driver code
    public static void Main()
    {
        String str = "ab..e.c.a";
        char[] s = str.ToCharArray();
        smallestPalindrome(s);
    }
}
// This code is contributed by PrinciRaj1992


PHP




<?php
// PHP program to get lexicographically
// smallest palindrome string
 
// Utility method to check str is
// possible palindrome after ignoring
function isPossiblePalindrome($str)
{
    $n = strlen($str);
    for ($i = 0; $i < $n / 2; $i++)
    {
        /* If both left and right
        character are not dot and
        they are not equal also, then
        it is not possible to make this
        string a palindrome */
        if ($str[$i] != '.' &&
            $str[$n - $i - 1] != '.' &&
            $str[$i] != $str[$n - $i - 1])
            return false;
    }
 
    return true;
}
 
// Returns lexicographically smallest
// palindrome string, if possible
function smallestPalindrome($str)
{
    if (!isPossiblePalindrome($str))
        return "Not Possible";
 
    $n = strlen($str);
 
    // loop through character of string
    for ($i= 0; $i < $n; $i++)
    {
        if ($str[$i] == '.')
        {
            // if one of character is dot,
            // replace dot with other character
            if ($str[$n - $i - 1] != '.')
                $str[$i] = $str[$n - $i - 1];
 
            // if both character are dot,
            // then replace them with
            // smallest character 'a'
            else
                $str[$i] = $str[$n - $i - 1] = 'a';
        }
    }
 
    // return the result
    return $str;
}
 
// Driver code
$str = "ab..e.c.a";
echo smallestPalindrome($str);
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
 
// Javascript program to get lexicographically
// smallest palindrome string
     
    // Utility method to check str is
    // possible palindrome after ignoring
    function isPossiblePalindrome(str)
    {
        let n = str.length;
        for (let i = 0; i < Math.floor(n / 2); i++)
        {
            /* If both left and right character
                are not dot and they are not
                equal also, then it is not
                possible to make this string a
                palindrome */
            if (str[i] != '.' &&
                str[n - i - 1] != '.' &&
                str[i] != str[n - i - 1])
                return false;
        }
           
        return true;
    }
     
    // Returns lexicographically smallest
    // palindrome string, if possible
    function smallestPalindrome(str)
    {
        if (!isPossiblePalindrome(str))
            document.write("Not Possible");
       
        let n = str.length;
           
        // loop through character of string
        for (let i = 0; i < n; i++)
        {
            if (str[i] == '.')
            {
                // if one of character is dot,
                // replace dot with other character
                if (str[n - i - 1] != '.')
                    str[i] = str[n - i - 1];
           
                // if both character are dot,
                // then replace them with
                // smallest character 'a'
                else
                    str[i] = str[n - i - 1] = 'a';
            }
        }
           
        // return the result
        for(let i = 0; i < n; i++)
            document.write(str[i] + "");
         
    }
     
    // Driver code
    let str="ab..e.c.a";
    let s = str.split("");
    smallestPalindrome(s);
     
    // This code is contributed by rag2127
     
</script>


Output

abcaeacba

Time complexity: O(n) where n is the length of the string.
Auxiliary Space complexity: O(1)

 



Previous Article
Next Article

Similar Reads

Check for Palindrome after every character replacement Query
Given a string str and Q queries. Each query contains a pair of integers (i1, i2) and a character 'ch'. We need to replace characters at indexes i1 and i2 with new character 'ch' and then tell if string str is palindrome or not. (0 &lt;= i1, i2 &lt; string_length) Examples: Input : str = "geeks" Q = 2 query 1: i1 = 3 ,i2 = 0, ch = 'e' query 2: i1 =
15+ min read
Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)
Write a program to check if a sentence is a palindrome or not. You can ignore white spaces and other characters to consider sentences as a palindrome. Examples: Input : str = "Too hot to hoot." Output : Sentence is palindrome. Input : str = "Abc def ghi jklm." Output : Sentence is not palindrome. Note: There may be multiple spaces and/or dots betwe
12 min read
Smallest length string with repeated replacement of two distinct adjacent
Given a string of any combination of three letters 'a', 'b', and 'c', find length of the smallest string that can be obtained by applying the following operation repeatedly: Take any two adjacent, distinct characters and replace them with the third. Examples: Input : cabOutput : 2We can select any two adjacent letters, say 'ca' and transform it int
15+ min read
Minimum array size after repeated replacement of even sum pair with sum
Given an array of size N. Choose a random pair of elements from the sequence such that their sum is even, delete those two elements from the sequence and insert their sum into the sequence instead in order to minimize the length of the array. Finally, print the minimum possible size of the array. Examples : Input : 88 98 1 7 3 Output : 2 By followi
6 min read
Program to find the quantity after mixture replacement
Given a container that has X liters of milk. Y liters of milk is drawn out and replaced with Y liters of water. This operation is done Z times. The task is to find out the quantity of milk left in the container.Examples: Input: X = 10 liters, Y = 2 liters, Z = 2 times Output: 6.4 liters Input: X = 25 liters, Y = 6 liters, Z = 3 times Output: 10.97
4 min read
Maximum number which can divide all array element after one replacement
Given an array arr, replace any one element in array with any other integer. The task is to return the maximum number which divides all elements in this array completely. Examples: Input: arr = [15, 9, 3]Output: 3Explanation: Here replace 15 with 3 so array becomes arr = [3, 9, 3] and now all elements in array are divisible by 3, so 3 is our answer
7 min read
Minimize count of peaks and troughs in given Array after at most one replacement
Given an array arr[] containing N positive integers, the task is to minimize the total count of peaks (elements having greater value than both the neighbours) and troughs (elements having less value than both the neighbours) by replacing at most one element of the given array with any value. Note: The first and the last element of the array cannot
12 min read
Character replacement after removing duplicates from a string
Given a string. The task is to replace each character of the minimized string with a character present at the index 'IND' of the original string. The minimized string is the string obtained by removing all duplicates from the original string keeping the order of elements the same. IND for any index in the minimized string is calculated as: IND = (s
7 min read
Smallest number after n removals after k day
Given a set containing all the natural numbers till infinity. You have k days and an array arr, on each day you remove a[i]th smallest natural number from the set, the task is to tell the smallest number in the set after k days. Examples: Input: N = 5, K = 1, arr[] = {1, 2, 4, 5, 6}Output: 3 Input: N = 5, K = 3, arr = {1, 3, 5, 6, 7}Output: 9 Appro
5 min read
Count all palindrome which is square of a palindrome
Given two positive integers L and R (represented as strings) where [Tex]1\leq L \leq R\leq10^{18} [/Tex]. The task is to find the total number of super-palindromes in the inclusive range [L, R]. A palindrome is called super-palindrome if it is a palindrome and also square of a palindrome. Examples: Input: L = "4", R = "1000" Output: 4 Explanation:
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg