Smallest Palindrome after replacement
Last Updated :
06 Jul, 2022
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>
Time complexity: O(n) where n is the length of the string.
Auxiliary Space complexity: O(1)
Similar Reads
Palindrome String Coding Problems
A string is called a palindrome if the reverse of the string is the same as the original one.Example: âmadamâ, âracecarâ, â12321â.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
2 min read
Palindrome String
Given a string s, the task is to check if it is palindrome or not.Example:Input: s = "abba"Output: 1Explanation: s is a palindromeInput: s = "abc" Output: 0Explanation: s is not a palindromeUsing Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left) and
13 min read
Check Palindrome by Different Language
Easy Problems on Palindrome
Sentence Palindrome
Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
9 min read
Check if actual binary representation of a number is palindrome
Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0âs are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
6 min read
Print longest palindrome word in a sentence
Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
14 min read
Count palindrome words in a sentence
Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
5 min read
Check if characters of a given string can be rearranged to form a palindrome
Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
14 min read
Lexicographically first palindromic string
Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
13 min read