Lexicographically largest string possible by repeatedly appending first character of two given strings
Given two strings S1 and S2 consisting of N and M lowercase characters, the task is to construct the lexicographically largest string by repeatedly appending the first character from either of the strings and remove that character from the chosen string.
Input: S1 = “dbcbb”, S2 = “cdbbb”
Let ans be the lexicographically largest string which is initially empty and perform the following steps to generate the resultant string:
Take first character from s1: ans = “d”, s1 = “bcbb”, s2 = “cdbbb”
Take first character from s2: ans = “dc”, s1 = “bcbb”, word2 = “dbbb”
Take first character from s2: ans = “dcd”, s1 = “bcbb”, word2 = “bbb”
Take first character from s1: ans = “dcdb”, s1 = “cbb”, word2 = “bbb”
Take first character from s1: ans = “dcbdc”, s1 = “bb”, word2 = “bbb”
Append the remaining 5 b’s from s1 and s2 at the end of ans. Therefore, print “dcdbcbbbbb” as the resultant string.
Input: S1 = “xyzxyz”, S2 = “xywzxyx”
Approach: The given problem can be solved by using the Two-Pointer Approach. Follow the steps below to solve the problem:
- Initialize an empty string, say merge as “” to store the lexicographically largest string.
- Initialize two pointers, say i as 0, j as 0 to traverse both the strings simultaneously.
- Traverse the string until either of the string has been used completely.
- If the substring word1[i, N – 1] is lexicographically greater than or equal to the substring word2[j, M – 1], then append the character word1[i] at the end of the string merge and increment the pointer i by 1.
- Otherwise, append the character word2[i] at the end of the string merge and increment the pointer j by 1.
- After completing the above steps, print the string merge as the resultant string.
Below is the implementation of the above approach:
Time Complexity: O(N*M)
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.