Open In App

Make palindromic string non-palindromic by rearranging its letters

Given string str containing lowercase alphabets (a – z). The task is to print the string after rearranging some characters such that the string becomes non-palindromic. If it’s impossible to make the string non-palindrome then print -1.

Examples: 

Input: str = “abba” 
Output: aabb

Input: str = “zzz” 
Output: -1 

Brute Force:

 Iterate through all possible permutations of the given string and check if the resulting string is non-palindromic.




#include <iostream>
#include <algorithm>
using namespace std;
 
bool isPalindrome(string s) {
    int i = 0, j = s.length() - 1;
    while (i < j) {
        if (s[i] != s[j]) {
            return false;
        }
        i++;
        j--;
    }
    return true;
}
 
string makeNonPalindrome(string s) {
    sort(s.begin(), s.end());
    do {
        if (!isPalindrome(s)) {
            return s;
        }
    } while (next_permutation(s.begin(), s.end()));
    return "-1";
}
 
int main() {
    string s = "abba";
    string result = makeNonPalindrome(s);
    cout << result << endl; // Output: aabb
    return 0;
}




import java.util.Arrays;
 
public class Main {
    public static boolean isPalindrome(String s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
 
    public static String makeNonPalindrome(String s) {
        char[] charArr = s.toCharArray();
        Arrays.sort(charArr);
        s = new String(charArr);
        do {
            if (!isPalindrome(s)) {
                return s;
            }
        } while (nextPermutation(charArr));
 
        return "-1";
    }
 
    public static boolean nextPermutation(char[] nums) {
        int i = nums.length - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }
        if (i < 0) {
            return false;
        }
        int j = nums.length - 1;
        while (nums[j] <= nums[i]) {
            j--;
        }
        swap(nums, i, j);
        reverse(nums, i + 1, nums.length - 1);
        return true;
    }
 
    public static void swap(char[] nums, int i, int j) {
        char temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
 
    public static void reverse(char[] nums, int i, int j) {
        while (i < j) {
            swap(nums, i, j);
            i++;
            j--;
        }
    }
 
    public static void main(String[] args) {
        String s = "abba";
        String result = makeNonPalindrome(s);
        System.out.println(result); // Output: aabb
    }
}




from itertools import permutations
 
def isPalindrome(s):
    i, j = 0, len(s) - 1
    while i < j:
        if s[i] != s[j]:
            return False
        i += 1
        j -= 1
    return True
 
def makeNonPalindrome(s):
    for p in permutations(sorted(s)):
        str = ''.join(p)
        if not isPalindrome(str):
            return str
    return "-1"
 
s = "abba"
result = makeNonPalindrome(s)
print(result) # Output: aabb




using System;
 
public class Program {
  public static bool IsPalindrome(string s)
  {
    int i = 0, j = s.Length - 1;
    while (i < j) {
      if (s[i] != s[j]) {
        return false;
      }
      i++;
      j--;
    }
    return true;
  }
 
  public static string MakeNonPalindrome(string s)
  {
    char[] arr = s.ToCharArray();
    Array.Sort(arr);
    do {
      if (!IsPalindrome(new string(arr))) {
        return new string(arr);
      }
    } while (NextPermutation(arr));
    return "-1";
  }
 
  public static bool NextPermutation(char[] arr)
  {
    int i = arr.Length - 2;
    while (i >= 0 && arr[i] >= arr[i + 1]) {
      i--;
    }
    if (i < 0) {
      return false;
    }
    int j = arr.Length - 1;
    while (arr[j] <= arr[i]) {
      j--;
    }
    char temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    int k = i + 1, l = arr.Length - 1;
    while (k < l) {
      temp = arr[k];
      arr[k] = arr[l];
      arr[l] = temp;
      k++;
      l--;
    }
    return true;
  }
 
  public static void Main()
  {
    string s = "abba";
    string result = MakeNonPalindrome(s);
    Console.WriteLine(result); // Output: aabb
  }
}




function isPalindrome(s) {
    let i = 0, j = s.length - 1;
    while (i < j) {
        if (s[i] != s[j]) {
            return false;
        }
        i++;
        j--;
    }
    return true;
}
 
function makeNonPalindrome(s) {
    let arr = s.split('').sort();
    do {
        let str = arr.join('');
        if (!isPalindrome(str)) {
            return str;
        }
    } while (nextPermutation(arr));
    return "-1";
}
 
function nextPermutation(arr) {
    let i = arr.length - 2;
    while (i >= 0 && arr[i] >= arr[i + 1]) {
        i--;
    }
     
    if (i < 0) {
        return false;
    }
     
    let j = arr.length - 1;
    while (j > i && arr[j] <= arr[i]) {
        j--;
    }
     
    [arr[i], arr[j]] = [arr[j], arr[i]];
     
    reverse(arr, i + 1);
     
    return true;
}
 
function reverse(arr, start) {
   let end = arr.length - 1;
   while(start < end){
      [arr[start],arr[end]] = [arr[end],arr[start]];
      start++;
      end--;
   }
}
 
let s = "abba";
let result = makeNonPalindrome(s);
console.log(result); // Output: aabb

Output
aabb

Time Complexity: O(n! * nlogn)

Auxiliary Space: O(n)

Approach: 

If all the characters in the string are the same then no matter how you rearrange the characters, the string will remain the same and will be palindromic. Now, if a non-palindromic arrangement exists, the best way to rearrange the characters is to sort the string which will form a continuous segment of the same characters and will never be palindromic. In order to reduce the time required to sort the string, we can store the frequencies of all 26 characters and print them in a sorted manner.

Steps to solve the problem:

Below is the implementation of the above approach: 




// CPP Program to rearrange letters of string
// to find a non-palindromic string if it exists
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the non-palindromic string
// if it exists, otherwise prints -1
void findNonPalinString(string s)
{
    int freq[26] = { 0 }, flag = 0;
 
    for (int i = 0; i < s.size(); i++) {
 
        // If all characters are not
        // same, set flag to 1
        if (s[i] != s[0])
            flag = 1;
 
        // Update frequency of the current character
        freq[s[i] - 'a']++;
    }
 
    // If all characters are same
    if (!flag)
        cout << "-1";
    else {
 
        // Print characters in sorted manner
        for (int i = 0; i < 26; i++)
            for (int j = 0; j < freq[i]; j++)
                cout << char('a' + i);
    }
}
 
// Driver Code
int main()
{
    string s = "abba";
 
    findNonPalinString(s);
 
    return 0;
}




// Java Program to rearrange letters of string
// to find a non-palindromic string if it exists
import java.io.*;
public class GfG
{
 
// Function to print the non-palindromic string
// if it exists, otherwise prints -1
static void findNonPalinString(char s[])
{
    int freq[] = new int[26];
    int flag = 0;
 
    for (int i = 0; i < s.length; i++)
    {
 
        // If all characters are not
        // same, set flag to 1
        if (s[i] != s[0])
            flag = 1;
 
        // Update frequency of
        // the current character
        freq[s[i] - 'a']++;
    }
 
    // If all characters are same
    if (flag == 0)
        System.out.println("-1");
    else
    {
 
        // Print characters in sorted manner
        for (int i = 0; i < 26; i++)
            for (int j = 0; j < freq[i]; j++)
                System.out.print((char)('a' + i));
    }
}
 
// Driver Code
public static void main(String[] args)
{
    String s = "abba";
     
    findNonPalinString(s.toCharArray());
}
}
 
// This code is contributed by
// Prerna Saini.




# Python3 Program to rearrange letters of string
# to find a non-palindromic string if it exists
 
# Function to print the non-palindromic string
# if it exists, otherwise prints -1
def findNonPalinString(s):
 
    freq = [0] * (26)
    flag = 0
 
    for i in range(0, len(s)):
 
        # If all characters are not same,
        # set flag to 1
        if s[i] != s[0]:
            flag = 1
 
        # Update frequency of the current
        # character
        freq[ord(s[i]) - ord('a')] += 1
 
    # If all characters are same
    if not flag:
        print("-1")
     
    else:
         
        # Print characters in sorted manner
        for i in range(0, 26):
            for j in range(0, freq[i]):
                print(chr(ord('a') + i),
                               end = "")
 
# Driver Code
if __name__ == "__main__":
 
    s = "abba"
    findNonPalinString(s)
 
# This code is contributed by
# Rituraj Jain




// C# Program to rearrange letters
// of string to find a non-palindromic
// string if it exists
using System;
 
class GfG
{
 
    // Function to print the
    // non-palindromic string
    // if it exists, otherwise
    // prints -1
    static void findNonPalinString(char []s)
    {
        int []freq = new int[26];
        int flag = 0;
     
        for (int i = 0; i < s.Length; i++)
        {
     
            // If all characters are not
            // same, set flag to 1
            if (s[i] != s[0])
                flag = 1;
     
            // Update frequency of
            // the current character
            freq[s[i] - 'a']++;
        }
     
        // If all characters are same
        if (flag == 0)
            Console.WriteLine("-1");
        else
        {
     
            // Print characters in sorted manner
            for (int i = 0; i < 26; i++)
                for (int j = 0; j < freq[i]; j++)
                        Console.Write((char)('a' + i));
        }
    }
     
    // Driver Code
    public static void Main()
    {
        string s = "abba";
         
        findNonPalinString(s.ToCharArray());
    }
}
 
// This code is contributed by Ryuga




<script>
 
// JavaScript Program to rearrange letters of string
// to find a non-palindromic string if it exists
 
// Function to print the non-palindromic string
// if it exists, otherwise prints -1
function findNonPalinString(s)
{
    var freq = Array.from({length: 26}, (_, i) => 0);
    var flag = 0;
 
    for (var i = 0; i < s.length; i++)
    {
 
        // If all characters are not
        // same, set flag to 1
        if (s[i] != s[0])
            flag = 1;
 
        // Update frequency of
        // the current character
        freq[s[i].charCodeAt(0) -
        'a'.charCodeAt(0)]++;
    }
 
    // If all characters are same
    if (flag == 0)
        document.write("-1");
    else
    {
 
        // Print characters in sorted manner
        for (var i = 0; i < 26; i++)
            for (var j = 0; j < freq[i]; j++)
                document.write(String.fromCharCode
                ('a'.charCodeAt(0) + i));
    }
}
 
// Driver Code
var s = "abba";
 
findNonPalinString(s.split(''));
 
// This code contributed by shikhasingrajput
 
</script>

Output
aabb

Complexity Analysis:


Article Tags :