
Consider STR1 = ”ca” and STR2 = ”db”. All the possible strings that can be constructed by merging “ca” and “db” are “cadb”, “cdab”, “cdba”, “dcab”, “dcba” and “dbca”, among them the lexicographically largest string is “dcba”. Hence, the answer is “dcba” in this case.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains the string ‘STR1’.
The second line of each test case contains the string ‘STR2’.
For each test case, print a single line containing a single string denoting the lexicographically largest string constructed by merging ‘STR1’ and ‘STR2’.
The output of each test case will be printed in a separate line.
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |STR1| <= 3000
1 <= |STR2| <= 3000
Strings 'STR1' and 'STR2' contain lowercase English letters only.
Where 'T' denotes the number of test cases, ‘STR1’ and ‘STR2’ represent the two given strings.
Time limit: 1 sec.
The idea is to use a recursive approach to find the lexicographically largest string constructed by merging both strings. We will merge STR1 and STR2 character by character. The recursive idea is clear that there are only two choices, either to choose the next character from the string STR1 or the string STR2 for any character in the merged string. Using this idea, we can construct the lexicographically largest string recursively.
We will define a function largestMergedString(STR1, STR2) to find the lexicographically largest merge of both strings. At each recursive call, we will find the next character to be included in the merged string. The next character should be from the lexicographically larger string between STR1 and STR2. Our approach will be to find the lexicographically greater string and includes its first character in the merged string.
We will merge STR1 and STR2 character by character. The idea is to observe the fact that it is always optimal to choose the next character of the merged string from the lexicographically larger string between STR1 and STR2. At each step, we will find out which string out of both strings is lexicographically greater and concatenate its first character to the end of the merged string.
Therefore, we will have to iterate till the length of strings STR1 and STR2 are more than 0. Now there will be two cases:
In the end, we will return the lexicographically largest merged string of STR1 and STR2.