Open In App

Find two unique Palindrome Strings using given String characters

Last Updated : 19 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given a string S of two distinct characters as input, the task is to find two strings using characters of the given string, such that both strings are different from S and both should be a palindrome.

Examples:

Input: S = "xyyxxxx"
Output: yxxxxxy, xxyxyxx
Explanation: It can be verified that at least one of the output strings is different from S and both are palindrome.

Input: S="ab"      
Output: Not Possible

Approach: Implement the idea below to solve the problem:

The problem is observation based and can be solved via checking parity and frequency of both distinct characters in S. Below are the some observations by which we can conclude some rules. Considered X, Y are the frequencies of two distinct characters in S: 

  1. If the below conditions are satisfied, it can be verified that there will not be any two palindrome strings satisfying given conditions:
    • If any of X or Y is equal to 1.
    • Both X and Y are Odd.
  2. Rest of the cases except discussed above will have a guaranteed solution.
    • When Both X and Y are even: 
      Say X = 4, Y = 6 then two possible strings are "aabbbbbbaa" and "bbbaaaabbb" and both are different.
    • When either X or Y is odd:
      Say X = 3, Y = 6 then two possible strings are "bbbaaabbb" and "abbbabbba".

 Follow the steps mentioned below to implement the idea:

  • Check the parity of X and Y i.e., of two distinct characters.
  • Output answer according to discussed parities of X and Y above.

Below is the implementation of the above approach.

C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;

// Function to create palindrome of
// the given string
void createPalindrome(string str)
{
  // Hashmap for counting frequency
  // of characters
  map<char, int> map;

  // Loop for traversing on input string
  for (int i = 0; i < str.size(); i++)
  {
    if (map.find(str[i]) != map.end())
    {
      map[str[i]] += 1;
    }
    else
    {
      map[str[i]] = 1;
    }
  }

  char first = ' ', second = ' ';
  int X = 0, Y = 0;

  // Counter variable
  int counter = 1;

  // Map for traversing on map
  for (auto Set : map)
  {

    // Initializing first character
    // and its frequency
    if (counter == 1)
    {
      first = Set.first;
      X = Set.second;
      counter++;
    }

    // Initializing second character
    // and its frequency
    else
    {
      second = Set.first;
      Y = Set.second;
    }
  }

  // Checking for the conditions in
  // which two stringsare not possible
  if ((X == 1 || Y == 1) || (X % 2 == 1) && (Y % 2 == 1))
  {

    // Printing output as Not
    // Possible if conditions met
    cout << "Not Possible" << endl;
  }

  // Rest of the cases except in which
  // strings are not possible

  // If both X and Y are Even
  else if (X % 2 == 0 && Y % 2 == 0)
  {

    // Printing arrangements as below
    // aabbaa
    // baaaab
    for (int i = 1; i <= X / 2; i++)
      cout << first;
    for (int i = 1; i <= Y; i++)
      cout << second;
    for (int i = 1; i <= X / 2; i++)
      cout << first;
    cout << " ";

    for (int i = 1; i <= Y / 2; i++)
      cout << second;
    for (int i = 1; i <= X; i++)
      cout << first;
    for (int i = 1; i <= Y / 2; i++)
      cout << second;
  }

  // If either X or Y is odd
  else if (X % 2 != 0 || Y % 2 != 0)
  {

    if (X % 2 == 0)
    {
      for (int i = 1; i <= X / 2; i++)
        cout << first;
      for (int i = 1; i <= Y; i++)
        cout << second;
      for (int i = 1; i <= X / 2; i++)
        cout << first;
      cout << " ";
    }
    else
    {
      for (int i = 1; i <= Y / 2; i++)
        cout << second;
      for (int i = 1; i <= X; i++)
        cout << first;
      for (int i = 1; i <= Y / 2; i++)
        cout << second;
      cout << " ";
    }

    if (X % 2 == 0)
    {
      for (int i = 1; i <= Y / 2; i++)
        cout << second;
      for (int i = 1; i <= X / 2; i++)
        cout << first;
      cout << second;
      for (int i = 1; i <= X / 2; i++)
        cout << first;
      for (int i = 1; i <= Y / 2; i++)
        cout << second;
    }
    else
    {
      for (int i = 1; i <= X / 2; i++)
        cout << first;
      for (int i = 1; i <= Y / 2; i++)
        cout << second;
      cout << first;
      for (int i = 1; i <= Y / 2; i++)
        cout << second;
      for (int i = 1; i <= X / 2; i++)
        cout << first;
    }
  }
  cout << endl;
}

int main()
{
  // Code
  int i = 0, testCases = 3;
  string arr[] = {"baaaaaab", "aaabbbb", "aaaaaab"};
  // For the first string the output order may be
  // different because of the way values are sorted in
  // the dictionary

  while (i < testCases)
  {
    string str = arr[i];
    cout << "The original String is: "
      << str << endl;
    cout << "Palindrome String: ";

    // Function call
    createPalindrome(str);
    cout << endl;
    i++;
  }
}

// This code is contributed by akashish__
Java
// C++ code to implement the approach

import java.util.*;

public class GFG {

    // Driver code
    public static void main(String[] args)
    {
        int i = 0, testCases = 3;
        String arr[] = { "baaaaaab", "aaabbbb", "aaaaaab" };

        while (i < testCases) {
            String str = arr[i];
            System.out.println("The original String is: "
                               + str);
            System.out.print("Palindrome String: ");

            // Function call
            createPalindrome(str);
            System.out.println();
            i++;
        }
    }

    // Function to create palindrome of
    // the given string
    static void createPalindrome(String str)
    {
        // Hashmap for counting frequency
        // of characters
        HashMap<Character, Integer> map = new HashMap<>();

        // Loop for traversing on input string
        for (int i = 0; i < str.length(); i++) {
            map.put(str.charAt(i),
                    map.get(str.charAt(i)) == null
                        ? 1
                        : map.get(str.charAt(i)) + 1);
        }

        char first = ' ', second = ' ';
        int X = 0, Y = 0;

        // Counter variable
        int counter = 1;

        // Map for traversing on map
        for (Map.Entry<Character, Integer> set :
             map.entrySet()) {

            // Initializing first character
            // and its frequency
            if (counter == 1) {
                first = set.getKey();
                X = set.getValue();
                counter++;
            }

            // Initializing second character
            // and its frequency
            else {
                second = set.getKey();
                Y = set.getValue();
            }
        }

        // Checking for the conditions in
        // which two stringsare not possible
        if ((X == 1 || Y == 1)
            || (X % 2 == 1) && (Y % 2 == 1)) {

            // Printing output as Not
            // Possible if conditions met
            System.out.println("Not Possible");
        }

        // Rest of the cases except in which
        // strings are not possible

        // If both X and Y are Even
        else if (X % 2 == 0 && Y % 2 == 0) {

            // Printing arrangements as below
            // aabbaa
            // baaaab
            for (int i = 1; i <= X / 2; i++)
                System.out.print(first);
            for (int i = 1; i <= Y; i++)
                System.out.print(second);
            for (int i = 1; i <= X / 2; i++)
                System.out.print(first);
            System.out.print(" ");

            for (int i = 1; i <= Y / 2; i++)
                System.out.print(second);
            for (int i = 1; i <= X; i++)
                System.out.print(first);
            for (int i = 1; i <= Y / 2; i++)
                System.out.print(second);
        }

        // If either X or Y is odd
        else if (X % 2 != 0 || Y % 2 != 0) {

            if (X % 2 == 0) {
                for (int i = 1; i <= X / 2; i++)
                    System.out.print(first);
                for (int i = 1; i <= Y; i++)
                    System.out.print(second);
                for (int i = 1; i <= X / 2; i++)
                    System.out.print(first);
                System.out.print(" ");
            }
            else {
                for (int i = 1; i <= Y / 2; i++)
                    System.out.print(second);
                for (int i = 1; i <= X; i++)
                    System.out.print(first);
                for (int i = 1; i <= Y / 2; i++)
                    System.out.print(second);
                System.out.print(" ");
            }

            if (X % 2 == 0) {
                for (int i = 1; i <= Y / 2; i++)
                    System.out.print(second);
                for (int i = 1; i <= X / 2; i++)
                    System.out.print(first);
                System.out.print(second);
                for (int i = 1; i <= X / 2; i++)
                    System.out.print(first);
                for (int i = 1; i <= Y / 2; i++)
                    System.out.print(second);
            }
            else {
                for (int i = 1; i <= X / 2; i++)
                    System.out.print(first);
                for (int i = 1; i <= Y / 2; i++)
                    System.out.print(second);
                System.out.print(first);
                for (int i = 1; i <= Y / 2; i++)
                    System.out.print(second);
                for (int i = 1; i <= X / 2; i++)
                    System.out.print(first);
            }
        }
        System.out.println();
    }
}
Python3
# Function to create palindrome of
# the given string
def createPalindrome(str):
    # Hashmap for counting frequency
    # of characters
    map = {}

    # Loop for traversing on input string
    for i in range(len(str)):
        if ord(str[i]) in map:
            map[ord(str[i])] += 1
        else:
            map[ord(str[i])] = 1

    first = ' '
    second = ' '
    X = 0
    Y = 0

    # Counter variable
    counter = 1

    # Map for traversing on map
    for key in map:

        # Initializing first character
        # and its frequency
        if counter == 1:
            first = chr(key)
            X = map[key]
            counter += 1
        # Initializing second character
        # and its frequency
        else:
            second = chr(key)
            Y = map[key]

    # Checking for the conditions in
    # which two stringsare not possible
    if ((X == 1 or Y == 1)
            or (X % 2 == 1) and (Y % 2 == 1)):

        # Printing output as Not
        # Possible if conditions met
        print("Not Possible")

    # Rest of the cases except in which
    # strings are not possible

    # If both X and Y are Even
    elif (X % 2 == 0 and Y % 2 == 0):

        # Printing arrangements as below
        # aabbaa
        # baaaab
        for i in range(1, int(X / 2) + 1):
            print(first,end="")
        for i in range(1, Y + 1):
            print(second,end="")
        for i in range(1, int(X / 2) + 1):
            print(first,end="")
        print(" ",end="")

        for i in range(1, int(Y / 2) + 1):
            print(second,end="")
        for i in range(1, X + 1):
            print(first,end="")
        for i in range(1, int(Y / 2) + 1):
            print(second,end="")

    # If either X or Y is odd
    elif (X % 2 != 0 or Y % 2 != 0):

        if (X % 2 == 0):
            for i in range(1, int(X / 2) + 1):
                print(first,end="")
            for i in range(1, Y + 1):
                print(second,end="")
            for i in range(1, int(X / 2) + 1):
                print(first,end="")
            print(" ",end="")
        else:
            for i in range(1, int(Y / 2) + 1):
                print(second,end="")
            for i in range(1, X + 1):
                print(first,end="")
            for i in range(1, int(Y / 2) + 1):
                print(second,end="")
            print(" ",end="")

        if (X % 2 == 0):
            for i in range(1, int(Y / 2) + 1):
                print(second,end="")
            for i in range(1, int(X / 2) + 1):
                print(first,end="")     
            print(second,end="")
            for i in range(1, int(X / 2) + 1):
                print(first,end="")
              #for i in range(1, int(Y / 2) + 1):
                #print(second,end="");
        else:
            for i in range(1, int(X / 2) + 1):
                print(first,end="")
            for i in range(1, int(Y / 2) + 1):
                print(second,end="")
            print(first,end="")
            for i in range(1, int(Y / 2) + 1):
                print(second,end="")
              #for i in range(1, int(X / 2) + 1):
                  #print(first)
    print("")

  
i = 0
testCases = 3
arr = ["baaaaaab", "aaabbbb", "aaaaaab"]
# For the first string the output order may be
# different because of the way values are sorted in
# the dictionary

while (i < testCases):
  
  str = arr[i];
  print("The original String is: ",str)
  print("Palindrome String: ",end="")

  # Function call
  createPalindrome(str);
  i+=1

# This code is contributed by akashish__
C#
// C# code to implement the approach
using System;
using System.Collections;
using System.Collections.Generic;

public class GFG {

  // Function to create palindrome of
  // the given string
  static void createPalindrome(String str)
  {
    // Hashmap for counting frequency
    // of characters
    Dictionary<char, int> map
      = new Dictionary<char, int>();

    // Loop for traversing on input string
    for (int i = 0; i < str.Length; i++) {
      if (map.ContainsKey(str[i])) {
        map[str[i]] += 1;
      }
      else {
        map.Add(str[i], 1);
      }
    }

    char first = ' ', second = ' ';
    int X = 0, Y = 0;

    // Counter variable
    int counter = 1;

    // Map for traversing on map
    foreach(KeyValuePair<char, int> Set in map)
    {

      // Initializing first character
      // and its frequency
      if (counter == 1) {
        first = Set.Key;
        X = Set.Value;
        counter++;
      }

      // Initializing second character
      // and its frequency
      else {
        second = Set.Key;
        Y = Set.Value;
      }
    }

    // Checking for the conditions in
    // which two stringsare not possible
    if ((X == 1 || Y == 1)
        || (X % 2 == 1) && (Y % 2 == 1)) {

      // Printing output as Not
      // Possible if conditions met
      Console.WriteLine("Not Possible");
    }

    // Rest of the cases except in which
    // strings are not possible

    // If both X and Y are Even
    else if (X % 2 == 0 && Y % 2 == 0) {

      // Printing arrangements as below
      // aabbaa
      // baaaab
      for (int i = 1; i <= X / 2; i++)
        Console.Write(first);
      for (int i = 1; i <= Y; i++)
        Console.Write(second);
      for (int i = 1; i <= X / 2; i++)
        Console.Write(first);
      Console.Write(" ");

      for (int i = 1; i <= Y / 2; i++)
        Console.Write(second);
      for (int i = 1; i <= X; i++)
        Console.Write(first);
      for (int i = 1; i <= Y / 2; i++)
        Console.Write(second);
    }

    // If either X or Y is odd
    else if (X % 2 != 0 || Y % 2 != 0) {

      if (X % 2 == 0) {
        for (int i = 1; i <= X / 2; i++)
          Console.Write(first);
        for (int i = 1; i <= Y; i++)
          Console.Write(second);
        for (int i = 1; i <= X / 2; i++)
          Console.Write(first);
        Console.Write(" ");
      }
      else {
        for (int i = 1; i <= Y / 2; i++)
          Console.Write(second);
        for (int i = 1; i <= X; i++)
          Console.Write(first);
        for (int i = 1; i <= Y / 2; i++)
          Console.Write(second);
        Console.Write(" ");
      }

      if (X % 2 == 0) {
        for (int i = 1; i <= Y / 2; i++)
          Console.Write(second);
        for (int i = 1; i <= X / 2; i++)
          Console.Write(first);
        Console.Write(second);
        for (int i = 1; i <= X / 2; i++)
          Console.Write(first);
        for (int i = 1; i <= Y / 2; i++)
          Console.Write(second);
      }
      else {
        for (int i = 1; i <= X / 2; i++)
          Console.Write(first);
        for (int i = 1; i <= Y / 2; i++)
          Console.Write(second);
        Console.Write(first);
        for (int i = 1; i <= Y / 2; i++)
          Console.Write(second);
        for (int i = 1; i <= X / 2; i++)
          Console.Write(first);
      }
    }
    Console.WriteLine();
  }

  static public void Main()
  {

    // Code
    int i = 0, testCases = 3;
    string[] arr = { "baaaaaab", "aaabbbb", "aaaaaab" };
    // For the first string the output order may be
    // different because of the way values are sorted in
    // the dictionary

    while (i < testCases) {
      string str = arr[i];
      Console.WriteLine("The original String is: "
                        + str);
      Console.Write("Palindrome String: ");

      // Function call
      createPalindrome(str);
      Console.WriteLine();
      i++;
    }
  }
}

// This code is contributed by lokeshmvs21.
JavaScript
        // JavaScript code to implement the approach

        // Function to create palindrome of
        // the given string
        const createPalindrome = (str) => {
            // Hashmap for counting frequency
            // of characters
            let map = {};

            // Loop for traversing on input string
            for (let i = 0; i < str.length; i++) {
                map[str.charCodeAt(i)] = str.charCodeAt(i) in map ? map[str.charCodeAt(i)] + 1
                    : 1;
            }

            let first = ' ', second = ' ';
            let X = 0, Y = 0;

            // Counter variable
            let counter = 1;

            // Map for traversing on map
            for (let key in map) {

                // Initializing first character
                // and its frequency
                if (counter == 1) {
                    first = String.fromCharCode(key);
                    X = map[key];
                    counter++;
                }

                // Initializing second character
                // and its frequency
                else {
                    second = String.fromCharCode(key);
                    Y = map[key];
                }
            }

            // Checking for the conditions in
            // which two stringsare not possible
            if ((X == 1 || Y == 1)
                || (X % 2 == 1) && (Y % 2 == 1)) {

                // Printing output as Not
                // Possible if conditions met
                console.log("Not Possible<br/>");
            }

            // Rest of the cases except in which
            // strings are not possible

            // If both X and Y are Even
            else if (X % 2 == 0 && Y % 2 == 0) {

                // Printing arrangements as below
                // aabbaa
                // baaaab
                for (let i = 1; i <= parseInt(X / 2); i++)
                    console.log(first);
                for (let i = 1; i <= Y; i++)
                    console.log(second);
                for (let i = 1; i <= parseInt(X / 2); i++)
                    console.log(first);
                console.log(" ");

                for (let i = 1; i <= parseInt(Y / 2); i++)
                    console.log(second);
                for (let i = 1; i <= X; i++)
                    console.log(first);
                for (let i = 1; i <= parseInt(Y / 2); i++)
                    console.log(second);
            }

            // If either X or Y is odd
            else if (X % 2 != 0 || Y % 2 != 0) {

                if (X % 2 == 0) {
                    for (let i = 1; i <= parseInt(X / 2); i++)
                        console.log(first);
                    for (let i = 1; i <= Y; i++)
                        console.log(second);
                    for (let i = 1; i <= parseInt(X / 2); i++)
                        console.log(first);
                    console.log(" ");
                }
                else {
                    for (let i = 1; i <= parseInt(Y / 2); i++)
                        console.log(second);
                    for (let i = 1; i <= X; i++)
                        console.log(first);
                    for (let i = 1; i <= parseInt(Y / 2); i++)
                        console.log(second);
                    console.log(" ");
                }

                if (X % 2 == 0) {
                    for (let i = 1; i <= parseInt(Y / 2); i++)
                        console.log(second);
                    for (let i = 1; i <= parseInt(X / 2); i++)
                        console.log(first);
                    console.log(second);
                    for (let i = 1; i <= parseInt(X / 2); i++)
                        console.log(first);
                    for (let i = 1; i <= parseInt(Y / 2); i++)
                        console.log(second);
                }
                else {
                    for (let i = 1; i <= parseInt(X / 2); i++)
                        console.log(first);
                    for (let i = 1; i <= parseInt(Y / 2); i++)
                        console.log(second);
                    console.log(first);
                    for (let i = 1; i <= parseInt(Y / 2); i++)
                        console.log(second);
                    for (let i = 1; i <= parseInt(X / 2); i++)
                        console.log(first);
                }
            }
            console.log("<br/>");
        }

        // Driver code
        let i = 0, testCases = 3;
        let arr = ["baaaaaab", "aaabbbb", "aaaaaab"];

        while (i < testCases) {
            let str = arr[i];
            console.log(`The original String is: ${str}<br/>`);
            console.log("Palindrome String: ");

            // Function call
            createPalindrome(str);
            console.log("<br/>");
            i++;
        }

        // This code is contributed by rakeshsahni

Output
The original String is: baaaaaab
Palindrome String: aaabbaaa baaaaaab

The original String is: aaabbbb
Palindrome String: bbaaabb abbabba

The original String is: aaaaaab
Palindrome String: Not Possible

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article

Similar Reads