Print the last character of lexicographically smallest non-palindromic permutation of a string
Last Updated :
22 Jun, 2021
Given string str, the task is to print the last character of the lexicographically smallest non-palindromic permutation of the given string. If no such permutation exists, print “-1”.
Examples:
Input: str = “deepqvu”
Output: v
Explanation: The string “deepquv” is the lexicographically smallest permutation which is not a palindrome.
Therefore, the last character is v.
Input: str = “zyxaaabb”
Output: z
Explanation: The string “aaabbxyz” is the lexicographically smallest permutation which is not a palindrome.
Therefore, the last character is z.
Naive Approach: The simplest approach to solve the problem is to generate all possible permutations of the given string and for each permutation, check if it is a palindrome or not. Among all non-palindromic permutations obtained, print the last character of lexicographically the smallest permutation. Follow the steps below:
- Sort the given string str.
- Check all the subsequent permutations of the string for the palindrome using a function next_permutation().
- If there exists any permutation which is non-palindromic, then print its last character.
- Otherwise, print “-1”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPalin(string s, int N)
{
for ( int i = 0; i < N; i++) {
if (s[i] != s[N - i - 1]) {
return false ;
}
}
return true ;
}
void lexicographicSmallestString(
string s, int N)
{
if (N == 1) {
cout << "-1" ;
}
sort(s.begin(), s.end());
int flag = 0;
if (isPalin(s, N) == false )
flag = 1;
if (!flag) {
while (next_permutation(s.begin(),
s.end())) {
if (isPalin(s, N) == false ) {
flag = 1;
break ;
}
}
}
if (flag == 1) {
int lastChar = s.size() - 1;
cout << s[lastChar] << ' ' ;
}
else {
cout << "-1" ;
}
}
int main()
{
string str = "deepqvu" ;
int N = str.length();
lexicographicSmallestString(str, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static boolean isPalin(String s,
int N)
{
for ( int i = 0 ; i < N; i++)
{
if (s.charAt(i) !=
s.charAt(N - i - 1 ))
{
return false ;
}
}
return true ;
}
static boolean next_permutation( char [] p)
{
for ( int a = p.length - 2 ;
a >= 0 ; --a)
if (p[a] < p[a + 1 ])
for ( int b = p.length - 1 ;; --b)
if (p[b] > p[a])
{
char t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1 ;
a < b; ++a, --b)
{
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true ;
}
return false ;
}
static String sortString(String inputString)
{
char tempArray[] =
inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
static void lexicographicSmallestString(String s,
int N)
{
if (N == 1 )
{
System.out.print( "-1" );
}
s = sortString(s);
int flag = 0 ;
if (isPalin(s, N) == false )
flag = 1 ;
if (flag != 0 )
{
while (next_permutation(s.toCharArray()))
{
if (isPalin(s, N) == false )
{
flag = 1 ;
break ;
}
}
}
if (flag == 1 )
{
int lastChar = s.length() - 1 ;
System.out.print(s.charAt(lastChar) + " " );
}
else
{
System.out.print( "-1" );
}
}
public static void main(String[] args)
{
String str = "deepqvu" ;
int N = str.length();
lexicographicSmallestString(str, N);
}
}
|
Python3
def isPalin(s, N):
for i in range (N):
if (s[i] ! = s[N - i - 1 ]):
return False ;
return True ;
def next_permutation(p):
for a in range ( len (p) - 2 , 0 , - 1 ):
if (p[a] < p[a + 1 ]):
for b in range ( len (p) - 1 , - 1 ):
if (p[b] > p[a]):
t = p[a];
p[a] = p[b];
p[b] = t;
for a in range (a + 1 ,
a < b,):
b = len (p) - 1 ;
if (a < b):
t = p[a];
p[a] = p[b];
p[b] = t;
b - = 1 ;
return True ;
return False ;
def sortString(inputString):
tempArray = ''.join( sorted (inputString));
return tempArray;
def lexicographicSmallestString(s, N):
if (N = = 1 ):
print ( "-1" );
s = sortString(s);
flag = 0 ;
if (isPalin(s, N) = = False ):
flag = 1 ;
if (flag ! = 0 ):
while (next_permutation(s)):
if (isPalin(s, N) = = False ):
flag = 1 ;
break ;
if (flag = = 1 ):
lastChar = len (s) - 1 ;
print (s[lastChar],
end = "");
else :
print ( "-1" );
if __name__ = = '__main__' :
str = "deepqvu" ;
N = len ( str );
lexicographicSmallestString( str , N);
|
C#
using System;
class GFG{
static bool isPalin(String s,
int N)
{
for ( int i = 0; i < N; i++)
{
if (s[i] !=
s[N - i - 1])
{
return false ;
}
}
return true ;
}
static bool next_permutation( char [] p)
{
for ( int a = p.Length - 2;
a >= 0; --a)
if (p[a] < p[a + 1])
for ( int b = p.Length - 1;; --b)
if (p[b] > p[a])
{
char t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.Length - 1;
a < b; ++a, --b)
{
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true ;
}
return false ;
}
static String sortString(String inputString)
{
char []tempArray =
inputString.ToCharArray();
Array.Sort(tempArray);
return new String(tempArray);
}
static void lexicographicSmallestString(String s,
int N)
{
if (N == 1)
{
Console.Write( "-1" );
}
s = sortString(s);
int flag = 0;
if (isPalin(s, N) == false )
flag = 1;
if (flag != 0)
{
while (next_permutation(s.ToCharArray()))
{
if (isPalin(s, N) == false )
{
flag = 1;
break ;
}
}
}
if (flag == 1)
{
int lastChar = s.Length - 1;
Console.Write(s[lastChar] + " " );
}
else
{
Console.Write( "-1" );
}
}
public static void Main(String[] args)
{
String str = "deepqvu" ;
int N = str.Length;
lexicographicSmallestString(str, N);
}
}
|
Javascript
<script>
function isPalin(s, N) {
for ( var i = 0; i < N; i++) {
if (s[i] !== s[N - i - 1]) {
return false ;
}
}
return true ;
}
function next_permutation(p) {
for ( var a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for ( var b = p.length - 1; ; --b)
if (p[b] > p[a]) {
var t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true ;
}
return false ;
}
function sortString(inputString) {
var tempArray = inputString.split( "" );
tempArray.sort();
return tempArray.join( "" );
}
function lexicographicSmallestString(s, N) {
if (N === 1) {
document.write( "-1" );
}
s = sortString(s);
var flag = 0;
if (isPalin(s, N) === false ) flag = 1;
if (flag !== 0) {
while (next_permutation(s.split( "" ))) {
if (isPalin(s, N) === false ) {
flag = 1;
break ;
}
}
}
if (flag === 1) {
var lastChar = s.length - 1;
document.write(s[lastChar] + " " );
}
else {
document.write( "-1" );
}
}
var str = "deepqvu" ;
var N = str.length;
lexicographicSmallestString(str, N);
</script>
|
Time Complexity: O(N*N!)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to store the frequencies of each character of the given string str. If all the characters are the same, then print “-1”. Otherwise, print the largest character of the given string str.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void lexicographicSmallestString(
string s, int N)
{
map< char , int > M;
for ( char ch : s) {
M[ch]++;
}
if (M.size() == 1) {
cout << "-1" ;
}
else {
auto it = M.rbegin();
cout << it->first;
}
}
int main()
{
string str = "deepqvu" ;
int N = str.length();
lexicographicSmallestString(str, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static void lexicographicSmallestString(String s,
int N)
{
SortedMap<Character,
Integer> M = new TreeMap<Character,
Integer>();
char [] str = s.toCharArray();
for ( char c : str)
{
if (M.containsKey(c))
{
M.put(c, M.get(c) + 1 );
}
else
{
M.put(c, 1 );
}
}
if (M.size() == 1 )
{
System.out.print( "-1" );
}
else
{
System.out.print( M.lastKey() );
}
}
public static void main (String[] args)
{
String str = "deepqvu" ;
int N = str.length();
lexicographicSmallestString(str, N);
}
}
|
Python3
def lexicographicSmallestString(s, N):
M = {}
for ch in s:
M[ch] = M.get(ch, 0 ) + 1
if len (M) = = 1 :
print ( "-1" )
else :
x = list (M.keys())[ - 2 ]
print (x)
if __name__ = = '__main__' :
str = "deepqvu"
N = len ( str )
lexicographicSmallestString( str , N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void lexicographicSmallestString(String s,
int N)
{
SortedDictionary< char ,
int > M = new SortedDictionary< char ,
int >();
char [] str = s.ToCharArray();
foreach ( char c in str)
{
if (M.ContainsKey(c))
{
M = M + 1;
}
else
{
M.Add(c, 1);
}
}
if (M.Count == 1)
{
Console.Write( "-1" );
}
else
{
int count = 0;
foreach (KeyValuePair< char ,
int > m in M)
{
count++;
if (count == M.Count)
Console.Write(m.Key);
}
}
}
public static void Main(String[] args)
{
String str = "deepqvu" ;
int N = str.Length;
lexicographicSmallestString(str, N);
}
}
|
Javascript
<script>
function lexicographicSmallestString(s,N)
{
let M = new Map();
let str = s.split( "" );
for (let c=0;c< str.length;c++)
{
if (M.has(str))
{
M.set(str, M.get(str) + 1);
}
else
{
M.set(str, 1);
}
}
if (M.size == 1)
{
document.write( "-1" );
}
else
{
let temp=Array.from(M)
document.write( temp[temp.length-2][0] );
}
}
let str = "deepqvu" ;
let N = str.length;
lexicographicSmallestString(str, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(26)
Share your thoughts in the comments
Please Login to comment...