Lexicographically smallest string possible by merging two sorted strings

• Difficulty Level : Medium
• Last Updated : 01 Jun, 2021

Given two sorted strings S1 and S2 of lengths N and M respectively, the task is to construct lexicographically the smallest string possible by merging the two given strings and not changing the order of occurrence of characters.

Examples:

Input: S1 = “eefgkors”, S2 = “eegks”
Explanation:
String “eeeefggkkorss” is lexicographically the smallest string that can be formed after merging the two given string S1 and S2.

Input: S1 = “aabcdtx”, S2 = “achilp”
Output: “aaabccdhilptx”

Naive Approach: The simplest approach is to concatenate the given two strings and sort the resultant string to get lexicographically the smallest string.

Time Complexity: O(N + M)*log(N + M))
Auxiliary Space: O(N + M)

Efficient Approach: The above approach can be optimized by using the Two-Pointer technique by comparing characters of the given strings and then, construct the required string accordingly.
Follow the steps below to solve the problem:

• Initialize two pointers, say ptr1 and ptr2, pointing towards the beginning of both the strings S1 and S2 respectively.
• Initialize a string ans = â€œ”, to store the resultant lexicographically the smallest string.
• Iterate until ptr1 is less than N and ptr2 is less than M and perform the following steps:
• If S1[ptr1] is less than the S2[ptr2], then append the character S1[ptr1] to the string ans. Increment ptr1.
• Otherwise, append the character S2[ptr2] to the string ans. Increment ptr2.
• After completing the above steps, one of the pointers doesn’t reach the end of the string.
• Therefore, add all the remaining characters of the string to the end of the string ans.
• Print ans as the resultant string.

Below is the implementation of the above approach:

C++14

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to find lexicographically``// smallest string possible by merging``// two sorted strings``void` `mergeStrings(string s1, string s2)``{``    ``// Stores length of string s1``    ``int` `len1 = s1.size();` `    ``// Stores length of string s2``    ``int` `len2 = s2.size();` `    ``// Pointer to beginning``    ``// of string1 i.e., s1``    ``int` `pntr1 = 0;` `    ``// Pointer to beginning``    ``// of string2 i.e., s2``    ``int` `pntr2 = 0;` `    ``// Stores the final string``    ``string ans = ``""``;` `    ``// Traverse the strings``    ``while` `(pntr1 < len1 && pntr2 < len2) {` `        ``// Append the smaller of the``        ``// two current characters``        ``if` `(s1[pntr1] < s2[pntr2]) {``            ``ans += s1[pntr1];``            ``pntr1++;``        ``}` `        ``else` `{``            ``ans += s2[pntr2];``            ``pntr2++;``        ``}``    ``}` `    ``// Append the remaining characters``    ``// of any of the two strings``    ``if` `(pntr1 < len1) {``        ``ans += s1.substr(pntr1, len1);``    ``}``    ``if` `(pntr2 < len2) {``        ``ans += s2.substr(pntr2, len2);``    ``}` `    ``// Print the final string``    ``cout << ans;``}` `// Driver Code``int` `main()``{``    ``string S1 = ``"abdcdtx"``;``    ``string S2 = ``"achilp"``;` `    ``// Function Call``    ``mergeStrings(S1, S2);` `    ``return` `0;``}`

Java

 `// Java program for the above approach``import` `java.io.*;` `class` `GFG{``    ` `// Function to find lexicographically``// smallest string possible by merging``// two sorted strings``static` `void` `mergeStrings(String s1, String s2)``{` `    ``// Stores length of string s1``    ``int` `len1 = s1.length();``    ` `    ``// Stores length of string s2``    ``int` `len2 = s2.length();``    ` `    ``// Pointer to beginning``    ``// of string1 i.e., s1``    ``int` `pntr1 = ``0``;``    ` `    ``// Pointer to beginning``    ``// of string2 i.e., s2``    ``int` `pntr2 = ``0``;``    ` `    ``// Stores the final string``    ``String ans = ``""``;``    ` `    ``// Traverse the strings``    ``while` `(pntr1 < len1 && pntr2 < len2)``    ``{``    ` `        ``// Append the smaller of the``        ``// two current characters``        ``if` `(s1.charAt(pntr1) < s2.charAt(pntr2))``        ``{``            ``ans += s1.charAt(pntr1);``            ``pntr1++;``        ``}``        ` `        ``else``        ``{``            ``ans += s2.charAt(pntr2);``            ``pntr2++;``        ``}``    ``}``    ` `    ``// Append the remaining characters``    ``// of any of the two strings``    ``if` `(pntr1 < len1)``    ``{``        ``ans += s1.substring(pntr1, len1);``    ``}``    ``if` `(pntr2 < len2)``    ``{``        ``ans += s2.substring(pntr2, len2);``    ``}``    ` `    ``// Print the final string``    ``System.out.println(ans);``}` `// Driver Code``public` `static` `void` `main (String[] args)``{``    ``String S1 = ``"abdcdtx"``;``    ``String S2 = ``"achilp"``;` `    ``// Function Call``    ``mergeStrings(S1, S2);``}``}` `// This code is contributed by sanjoy_62`

Python3

 `# Python3 program for the above approach` `# Function to find lexicographically``# smallest possible by merging``# two sorted strings``def` `mergeStrings(s1, s2):``  ` `    ``# Stores length of s1``    ``len1 ``=` `len``(s1)` `    ``# Stores length of s2``    ``len2 ``=` `len``(s2)` `    ``# Pointer to beginning``    ``# of string1 i.e., s1``    ``pntr1 ``=` `0` `    ``# Pointer to beginning``    ``# of string2 i.e., s2``    ``pntr2 ``=` `0` `    ``# Stores the final string``    ``ans ``=` `""` `    ``# Traverse the strings``    ``while` `(pntr1 < len1 ``and` `pntr2 < len2):` `        ``# Append the smaller of the``        ``# two current characters``        ``if` `(s1[pntr1] < s2[pntr2]):``            ``ans ``+``=` `s1[pntr1]``            ``pntr1 ``+``=` `1``        ``else``:``            ``ans ``+``=` `s2[pntr2]``            ``pntr2 ``+``=` `1` `    ``# Append the remaining characters``    ``# of any of the two strings``    ``if` `(pntr1 < len1):``        ``ans ``+``=` `s1[pntr1:pntr1 ``+` `len1]` `    ``if` `(pntr2 < len2):``        ``ans ``+``=` `s2[pntr2:pntr2 ``+` `len2]` `    ``# Print the final string``    ``print` `(ans)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``S1 ``=` `"abdcdtx"``    ``S2 ``=` `"achilp"` `    ``# Function Call``    ``mergeStrings(S1, S2)` `# This code is contributed by mohit kumar 29.`

C#

 `// C# program for the above approach``using` `System;``class` `GFG``{``  ` `  ``// Function to find lexicographically``  ``// smallest string possible by merging``  ``// two sorted strings``  ``static` `void` `mergeStrings(``string` `s1, ``string` `s2)``  ``{``    ` `    ``// Stores length of string s1``    ``int` `len1 = s1.Length;` `    ``// Stores length of string s2``    ``int` `len2 = s2.Length;` `    ``// Pointer to beginning``    ``// of string1 i.e., s1``    ``int` `pntr1 = 0;` `    ``// Pointer to beginning``    ``// of string2 i.e., s2``    ``int` `pntr2 = 0;` `    ``// Stores the final string``    ``string` `ans = ``""``;` `    ``// Traverse the strings``    ``while` `(pntr1 < len1 && pntr2 < len2) {` `      ``// Append the smaller of the``      ``// two current characters``      ``if` `(s1[pntr1] < s2[pntr2]) {``        ``ans += s1[pntr1];``        ``pntr1++;``      ``}` `      ``else` `{``        ``ans += s2[pntr2];``        ``pntr2++;``      ``}``    ``}` `    ``// Append the remaining characters``    ``// of any of the two strings``    ``if` `(pntr1 < len1) {``      ``ans += s1.Substring(pntr1, len1 - pntr1);``    ``}``    ``if` `(pntr2 < len2) {``      ``ans += s2.Substring(pntr2, len2 - pntr2);``    ``}` `    ``// Print the final string``    ``Console.WriteLine(ans);``  ``}` `  ``// Driver Code``  ``public` `static` `void` `Main()``  ``{``    ``string` `S1 = ``"abdcdtx"``;``    ``string` `S2 = ``"achilp"``;` `    ``// Function Call``    ``mergeStrings(S1, S2);``  ``}``}` `// This code is contributed by ukasp.`

Javascript

 ``

Output:

`aabcdcdhilptx`

Time Complexity: O(N + M)
Auxiliary Space: O(N + M)

My Personal Notes arrow_drop_up