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.
Examples:
Input: S = “dbcbb”, T = “cdbbb”
Output : dcdbcbbbbbInput : 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[0] + 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:
C++
|
gforgeekseeks
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.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
Lexicographically Largest Possible By Merging Two Strings By Adding One Character At A Time ~ Cnc Software >>>>> Download Now
ReplyDelete>>>>> Download Full
Lexicographically Largest Possible By Merging Two Strings By Adding One Character At A Time ~ Cnc Software >>>>> Download LINK
>>>>> Download Now
Lexicographically Largest Possible By Merging Two Strings By Adding One Character At A Time ~ Cnc Software >>>>> Download Full
>>>>> Download LINK D0