Open In App

Lexicographically smallest string possible by merging two sorted strings

Last Updated : 01 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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”
Output: “eeeefggkkorss”
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 <bits/stdc++.h>
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




<script>
     
// Javascript program for the above approach
 
// Function to find lexicographically
// smallest string possible by merging
// two sorted strings
function mergeStrings( s1,  s2)
{
    // Stores length of string s1
    var len1 = s1.length;
 
    // Stores length of string s2
    var len2 = s2.length;
 
    // Pointer to beginning
    // of string1 i.e., s1
    var pntr1 = 0;
 
    // Pointer to beginning
    // of string2 i.e., s2
    var pntr2 = 0;
 
    // Stores the final string
    var 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
    document.write( ans);
}
 
// Driver Code
var S1 = "abdcdtx";
var S2 = "achilp";
// Function Call
mergeStrings(S1, S2);
 
</script>


Output: 

aabcdcdhilptx

 

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

 



Similar Reads

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 : dcdbcbbbbb Input
5 min read
Build lexicographically smallest String from two given Strings
Given two strings X and Y of lowercase letters, of length N and M respectively, the task is to build another string Z by performing two types of operations: Choose any character from the string X, remove it from X, and add it to the end of Z.Choose any character from the string Y, remove it from Y, and add it to the end of Z. Note: You can only K c
6 min read
Lexicographically largest string by merging identical adjacent letters into previous letter
Given a positive integer N representing a string of length N with only the letter 'z,' the task is to find the Lexicographically largest string by merging adjacent identical letters into a single letters of previous alphabet (e.g. Merging "zz" would become "y" and Merging "yy" would become "x" and so on). Note: "aa" cannot be further mergered. Exam
6 min read
Lexicographically smallest string possible by performing K operations on a given string
Given a string S of size N and a positive integer K, the task is to perform atmost K operations on string S to make it lexicographically smallest possible. In one operation, swap S[i] and S[j] and then change S[i] to any character, given 1 ? i &lt; j ? N. Examples: Input: S = "geek", K = 5Output: aaaaExplanation: In 1st operation: take i = 1 and j
8 min read
Lexicographically smallest string with period K possible by replacing '?'s from a given string
Given a string S consisting of N lowercase characters and character '?' and a positive integer K, the task is to replace each character '?' with some lowercase alphabets such that the given string becomes a period of K. If it is not possible to do so, then print "-1". A string is said to be a period of K if and only if the length of the string is a
9 min read
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. Examples: Input: S1 = "dbcbb", S2 = "cdbbb"Output: "dcdbcbbbbb"Explanation:Let ans be the lexic
6 min read
Find smallest Substring to be rearranged to make String lexicographically sorted
Given a string S, the task is to find out the length of the smallest substring of S that needs to be rearranged so that all the characters of the string S are in lexicographical order. Examples: Input: S = "aabbace"Output: 3Explanation: Rearranging "bba" to be "abb".S becomes "aaabbce" which is in lexicographical order. Input: S = "abez"Output: 0 A
4 min read
Efficiently merging two sorted arrays with O(1) extra space and O(NlogN + MlogM)
Given two sorted arrays, arr1[] and arr2[], the task is to merge them in O(Nlog(N) + Mlog(M)) time with O(1) extra space into a sorted array where N is the size of the first array arr1[] and M is the size of the second array arr2[]. Examples: Input: arr1[] = {1, 5, 9, 10, 15, 20}, arr2[] = {2, 3, 8, 13} Output: 1 2 3 5 8 9 10 13 15 20 Input: arr1[]
9 min read
Check if array can be divided into two subsequences merging whom makes Array sorted
Given an integer array A[] of size N, the task is to check if the array can be divided into two subsequences such that appending one of them at the end of the other makes the array sorted. A sub-sequence is a sequence that can be obtained from the array by deleting some or no elements from it. It may or may not be a continuous part of an array. Exa
8 min read
Merging two unsorted arrays in sorted order
Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list. Examples : Input : a[] = {10, 5, 15} b[] = {20, 3, 2} Output : Merge List : {2, 3, 5, 10, 15, 20} Input : a[] = {1, 10, 5, 15} b[] = {20, 0, 2}
12 min read