Largest palindromic string possible from given strings by rearranging the characters

Largest palindromic string possible from given strings by rearranging the characters

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

Given two strings S *and *P, the task is to find the largest palindrome possible string by choosing characters from the given strings S and P after rearranging the characters.

Note: *If many answers are possible, then find the lexicographically smallest *T with maximum length. 

Examples:

Input:_ S = “abad”, T = “eeff”_

_Output: _aefbfea

_Explanation: _

From the first string “aba” and from the second string “effe” are palindromes.

Use these two to make a new palindrome T “aefbfea” which is lexicographically smallest.

Also T is of maximum length possible.

Note:__“ada”, although this will give T of same length i.e., 7 but that won’t be lexicographically smallest.

Input:_ S = “aeabb”, T = “dfedf”_

Output:_ abdeffedba_

Explanation:

From the first string “abeba” and from the second string “dfefd”, are palindrome. Combine the two to get T: “abdeffedba” is lexicographically smallest.

Approach: The idea is to take all the characters from the strings S and P which are present** even** a number of times respectively. As the substrings, A and B of both the string have all characters which are present even number of times in S and P respectively to become the largest palindrome from parent string. Below are the steps:

  1. Take a single character from strings S and P, such that they will be present in the mid of palindromes taken from each string respectively. Place that unique element in mid of T.
  2. The possible cases to take a unique element from substring A and B are:
  • If a unique element is present in both A and B, then take both of them because it will increase the length of T by 2.
  • If unique elements are present in both S and P but not the same element, then take that which is small because that will make lexicographically the smallest palindrome T.
  • If no unique element is present in both, then make the string T just with elements from A and B.
  1. Use the unordered map to take count of characters occurring even number of times in parent string. Also, use another map to have count of characters to be used in making T.

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 largest palindrome

// possible from S and P after rearranging

// characters to make palindromic string T

string mergePalindromes(string S, string P)

{

// Using unordered_map to store

// frequency of elements

// mapT will have freq of elements of T

unordered_map<``**char**``, **int**``> mapS, mapP, mapT;

// Size of both the strings

**int** n = S.size(), m = P.size();

**for** (``**int** i = 0; i < n; i++) {

mapS[S[i]]++;

}

**for** (``**int** i = 0; i < m; i++) {

mapP[P[i]]++;

}

// Take all character in mapT which

// occur even number of times in

// respective strings & simultaneously

// update number of characters left in map

**for** (``**char** i = 'a'``; i <= 'z'``; i++) {

**if** (mapS[i] % 2 == 0) {

mapT[i] += mapS[i];

mapS[i] = 0;

}

**else** {

mapT[i] += mapS[i] - 1;

mapS[i] = 1;

}

**if** (mapP[i] % 2 == 0) {

mapT[i] += mapP[i];

mapP[i] = 0;

}

**else** {

mapT[i] += mapP[i] - 1;

mapP[i] = 1;

}

}

// Check if a unique character is

// present in both string S and P

**int** check = 0;

**for** (``**char** i = 'a'``; i <= 'z'``; i++) {

**if** (mapS[i] > 0 && mapP[i] > 0) {

mapT[i] += 2;

check = 1;

**break**``;

}

}

// Making string T in two halves

// half1 - first half

// half2 - second half

string half1 = ""``, half2 = ""``;

**for** (``**char** i = 'a'``; i <= 'z'``; i++) {

**for** (``**int** j = 0; (2 * j) < mapT[i]; j++) {

half1 += i;

half2 += i;

}

}

// Reverse the half2 to attach with half1

// to make palindrome T

reverse(half2.begin(), half2.end());

// If same unique element is present

// in both S and P, then taking that only

// which is already taken through mapT

**if** (check) {

**return** half1 + half2;

}

// If same unique element is not

// present in S and P, then take

// characters that make string T

// lexicographically smallest

**for** (``**char** i = 'a'``; i <= 'z'``; i++) {

**if** (mapS[i] > 0 || mapP[i] > 0) {

half1 += i;

**return** half1 + half2;

}

}

// If no unique element is

// present in both string S and P

**return** half1 + half2;

}

// Driver Code

**int** main()

{

// Given two strings S and P

string S = "aeabb"``;

string P = "dfedf"``;

// Function Call

cout << mergePalindromes(S, P);

**return** 0;

}

Output:

abdeffedba

Time Complexity:_ O(N), where N is the length of String S or P._

Auxiliary Space:_ O(N)_

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.

greedy mathematical strings greedy algorithms palindrome

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

A greedy algorithm is a simple

The Greedy Method is an approach for solving certain types of optimization problems. The greedy algorithm chooses the optimum result.

Generate a String of having N*N distinct non-palindromic Substrings

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

Minimum Count of Bit flips required to make a Binary String Palindromic

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

LeetCode: Longest Palindromic Substring With Manachar’s Algorithm

Question: Given a string s, find the longest palindromic substring in s. A palindrome is a word that reads the same forwards and backwards.

Greedy Algorithm | Fractional Knapsack Problem With Solution

What is Greedy Method Before discussing the Fractional Knapsack, we talk a bit about the Greedy Algorithm. Here is our main question is when we can solve a problem with Greedy Method? Each problem has some common characteristic, as like the...