Largest palindromic string possible from given strings by rearranging the characters
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.
Input: S = “abad”, T = “eeff”
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”
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:
- 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.
- 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.
- 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:
Time Complexity: O(N), where N is the length of String S or P.
Auxiliary Space: O(N)
Please Login to comment...