Lexicographically largest possible by merging two strings by adding one character at a time
Given two strings S and T, the task is to merge these two strings by adding one character at a time from the beginning of either string to form a resultant string. The resultant string should be lexicographically the largest string that can be formed by merging the strings S and T.
Input: S = “dbcbb”, T = “cdbbb”
Output : dcdbcbbbbb
Input : S = “geeks“, T = “forgeeks”
Output : gforgeekseeks
Approach: The simplest idea to solve the problem is to greedily select the first characters from the string which is lexicographically bigger than others. Therefore, Greedy algorithm and Recursion can be used to solve the problem. Follow the steps below to solve the problem:
- If either of the string lengths is 0, then return S + T as the answer.
- If S is lexicographically larger than T, then return S + largestMerge(S.substr(1), T).
- Otherwise, take the first character of T and call the recursive function largestMerge(S, T.substr(1)).
Below is the implementation of the above approach:
Time Complexity: O(M×N), where M and N are the length of string s1 and s2 respectively.
Auxiliary Space: O(1)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.