Given string str consisting of lowercase alphabets, the task is to construct the lexicographically smallest non-palindromic string by swapping any pair of adjacent characters from the string any number of times.
If the given string cannot be converted to a lexicographically smallest non-palindromic string, then print “-1”.
Examples:
Input: str = “djfbw”
Output: bdfjw
Explanation:
Perform the following swap operations to get the lexicographically smallest non-palindromic string:
Swap ‘b’ and ‘f’, str becomes “djbfw”
Swap ‘j’ and ‘b’, str becomes “dbjfw”
Swap ‘b’ and ‘d’, str becomes “bdjfw”
Swap ‘j’ and ‘f’, str becomes “bdfjw”.
Now “bdfjw” is the lexicographically smallest string which is not a palindrome.Input: str[] = “pppppp”
Output: -1
Naive Approach: The idea is to generate all possible permutations of the string and to check if they form palindrome or not. Print the smallest permutation among them.
Time Complexity: O(N*N!)
Auxiliary Space: O(N)
Efficient Approach: The idea is to check if lexicographically the smallest string possible from the given string is a palindrome or not. Below are the steps:
- To obtain lexicographically the smallest string, sort the given string to arrange the characters of the string in increasing order.
- Now, if the sorted string is a palindrome, then it means that the string has only one type of character and it can not be arranged to form a string which is not a palindrome.
- If it is not a palindrome, then the sorted string is lexicographically the smallest string which is not a palindrome.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the lexographically // smallest string which is non-palindrome void smallestNonPalindromic(string& s) { // Sort the given string sort(s.begin(), s.end()); // Store reverse of sorted string string reversestring = string(s.rbegin(), s.rend()); // Check if the sorted string is // palindromic or not if (s != reversestring) { cout << s; } else { cout << "-1"; } } // Driver Code int main() { // Given string str string str = "asmfjdeovnhekfnj"; // Function Call smallestNonPalindromic(str); return 0; } |
Java
// Java program for the above approach import java.util.*; class GFG{ // reverse string static String reverse(String input) { char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a); } // Method to sort a string alphabetically static String sortString(String inputString) { // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray); } // Function to find the lexographically // smallest String which is non-palindrome static void smallestNonPalindromic(String s) { // Sort the given String s = sortString(s); // Store reverse of sorted String String reverseString = reverse(s); // Check if the sorted String is // palindromic or not if (s != reverseString) { System.out.print(s); } else { System.out.print("-1"); } } // Driver Code public static void main(String[] args) { // Given String str String str = "asmfjdeovnhekfnj"; // Function Call smallestNonPalindromic(str); } } // This code is contributed by gauravrajput1 |
Python3
# Python3 program for the above approach # Function to find the lexographically # smallest string which is non-palindrome def smallestNonPalindromic(s): # Sort the given string s = sorted(s) # Store reverse of sorted string reversestring = s[::-1] # Check if the sorted string is # palindromic or not if (s != reversestring): print("".join(s)) else: print("-1") # Driver Code if __name__ == '__main__': # Given string str str = "asmfjdeovnhekfnj" # Function call smallestNonPalindromic(str) # This code is contributed by mohit kumar 29 |
C#
// C# program for the above approach using System; class GFG{ // Reverse string static String reverse(String input) { char[] a = input.ToCharArray(); int l, r = a.Length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("", a); } // Method to sort a string alphabetically static String sortString(String inputString) { // Convert input string to char array char []tempArray = inputString.ToCharArray(); // Sort tempArray Array.Sort(tempArray); // Return new sorted string return new String(tempArray); } // Function to find the lexographically // smallest String which is non-palindrome static void smallestNonPalindromic(String s) { // Sort the given String s = sortString(s); // Store reverse of sorted String String reverseString = reverse(s); // Check if the sorted String is // palindromic or not if (s != reverseString) { Console.Write(s); } else { Console.Write("-1"); } } // Driver Code public static void Main(String[] args) { // Given String str String str = "asmfjdeovnhekfnj"; // Function call smallestNonPalindromic(str); } } // This code is contributed by Amit Katiyar |
adeeffhjjkmnnosv
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Make the string lexicographically smallest and non palindromic by replacing exactly one character
- Count of Palindromic Strings possible by swapping of a pair of Characters
- Print the last character of lexicographically smallest non-palindromic permutation of a string
- Minimize replacements or swapping of same indexed characters required to make two given strings palindromic
- Make palindromic string non-palindromic by rearranging its letters
- Lexicographically smaller string by swapping at most one character pair
- Check if a string can be converted to another by swapping of adjacent characters of given type
- Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
- Make lexicographically smallest palindrome by substituting missing characters
- Generate lexicographically smallest string of 0, 1 and 2 with adjacent swaps allowed
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Smallest number possible by swapping adjacent even odd pairs
- Minimum characters to be replaced to make a string concatenation of a K-length palindromic string
- Swap all occurrences of two characters to get lexicographically smallest string
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Replace minimal number of characters to make all characters pair wise distinct
- Minimum non-adjacent pair flips required to remove all 0s from a Binary String
- Minimize replacement of characters to its nearest alphabet to make a string palindromic
- Length of longest Palindromic Subsequence of even length with no two adjacent characters same
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

