Make the string lexicographically smallest and non palindromic by swapping of adjacent pair of characters

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:

  1. To obtain lexicographically the smallest string, sort the given string to arrange the characters of the string in increasing order.
  2. 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.
  3. 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
chevron_right

Output: 
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:


Check out this Author's contributed articles.

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.



Article Tags :