Merge two strings | Practice | GeeksforGeeks

Given two strings S1 and S2 as input, the task is to merge them alternatively i.e. the first character of S1 then the first character of S2 and so on till the strings end.
NOTE: Add the whole string if other string is empty.
Example 1:
Input:
S1 = "Hello" S2 = "Bye"
Output: HBeylelo
Explanation: The characters of both the 
given strings are arranged alternatlively.

â€‹Example 2:
Input: 
S1 = "abc", S2 = "def"
Output: adbecf
Explanation: The characters of both the
given strings are arranged alternatlively.


Your Task:
You don't need to read input or print anything. Your task is to complete the function merge() which takes the strings S1 and S2 as input and returns the resultant string by merging both S1 and S2 alternatively starting from S1.

Expected Time Complexity: O(|S1| + |S2|).
Expected Auxiliary Space: O(1).

Constraints:
1<=|S1|, |S2| <=103
0
singhvatsal593 weeks ago
 
string merge (string S1, string S2){   // your code here   int i=0;   string result="" ;   for(int i=0;i<S1.length() || i<S2.length();i++){       if(i<S1.length()){           result+=S1[i];       }              if(i<S2.length()){           result+=S2[i];       }   }      return result;}
0
kshitijmagare194 weeks ago
class Solution {    StringBuilder merge(String S1, String S2)   {        // code here       StringBuilder str = new StringBuilder();       int s1 =S1.length();       int s2 = S2.length();       int j = 0;       int i;              if(s1<s2){           for(i = 0; i< s1;i++){               str.append(S1.charAt(i));               str.append(S2.charAt(i));               j = i + 1;           }           for(i = j ; i< s2;i++){               str.append(S2.charAt(i));           }                  }       else if(s1>s2){           for(i = 0; i< s2;i++){               str.append(S1.charAt(i));               str.append(S2.charAt(i));               j = i + 1;           }           for(i = j; i< s1;i++){               str.append(S1.charAt(i));           }                  }       else{           for(i = 0; i< s1;i++){               str.append(S1.charAt(i));               str.append(S2.charAt(i));           }       }              return str;   }} 
+1
codewithshoaib191 month ago
String merge(String S1, String S2)   {        // code here       String result = "";       int n1 = S1.length();       int n2 = S2.length();       if (n1 > n2) {           for (int i = 0; i < n2; i++) {               result += S1.charAt(i);               result += S2.charAt(i);           }           return result + S1.substring(n2);       }       for (int i = 0; i < n1; i++) {           result += S1.charAt(i);           result += S2.charAt(i);       }       return result + S2.substring(n1);   }
0
bsricharan2461 month ago
Python Easy & Fast Approach | Time Taken = 0.0/2.2
class Solution:   def merge(self, S1, S2):       # code here       res = ""       j=0       k=0       for i in range(0, min(len(S1), len(S2))*2,1):           if i%2 ==0:               res+=S1[j]               j+=1           else:               res+=S2[k]               k+=1       if len(S1) != len(S2):           if min(len(S1), len(S2)) == len(S1):               res+=S2[k:]           else:               res+=S1[j:]       return res
0
akanshasaraswat13 months ago
100% accurate 
String merge(String S1, String S2)   {        // code here       String merge = "";       int i=0; int j=0; int k=0;              while(i<S1.length() && j<S2.length()){           if(k%2==0){               merge = merge + S1.charAt(i);               i++;            }           else{               merge = merge + S2.charAt(j);               j++;           }           k++;       }              while(i<S1.length()){           merge = merge + S1.charAt(i);           i++;                  }                  while(j<S2.length()){           merge = merge + S2.charAt(j);j++;}                return merge;               }
+3
rahulpankaj97543 months ago
string merge (string S1, string S2)
{   
    string S="";
    int n1=S1.size();
    int n2=S2.size();
    int i=0,j=0;
     for(int k=0; k<n1+n2; k++)
     {  
         if(i<n1)
         {
           S+=S1[i];
         }
         if(j<n2)
         {
           S+=S2[i];
         }
         i++;
         j++;
     }
     return S;
}
0
anmol1neema4 months ago
 time taken -0.2
String merge(String S1, String S2)   {        // code here      int j=0,k=0, p=0;      int greatA=0, greatB =0;      int valA= S1.length();      int valB = S2.length();      int n = valA + valB;      char[] c = new char[n];      if(valA>valB){          greatA = valA-valB;      }else{          greatB = valB-valA;      }     for(int i=0;i<n;i++){        if(i%2==0 && j<valA){            c[i]= S1.charAt(j);            j++;        }else if(k<valB){            c[i] = S2.charAt(k);            k++;        }else if(greatA>0){            c[i] = S1.charAt(j);            j++;        }else if(greatB>0){             c[i] = S2.charAt(k);            k++;        }             }         String s = new String(c);    return s;         }
0
rajithrock4444445 months ago
Time Taken-→0.3/2.2
 
String s4="";       int len=0;       if(s1.length()>s2.length()){           len=s1.length();       }       else{           len=s2.length();       }       for(int i=0;i<len;i++){           if(i<s1.length()){             s4+=s1.charAt(i);             }                      if(i<s2.length()){               s4+=s2.charAt(i);           }       }              return s4;
+1
saptarshithe426 months ago
class Solution:
    def merge(self, s1, s2):
        # code here
        if ((len(s1) == 0) or (len(s2) == 0)):
            return (s1 + s2)
            
        s = ""
        for i in range(min(len(s1), len(s2))):
            s = s + s1[i] + s2[i]
        if (len(s1) > len(s2)):
            rem = s1[i + 1:]
        else:
            rem = s2[i+1:]
        return (s + rem)
0
badgujarsachin836 months ago
string merge (string S1, string S2)
{
    // your code here
    string ss="";
    bool ans=true;
    int i=0;
    int j=0;
    while( i<S1.size() && j<S2.size()){
       if(ans==true){
           ss+=S1[i];
           ans=false;
           i++;
       }
       if(ans==false){
           ss+=S2[j];
           ans=true;
           j++;
       }
    }
    while(i<S1.size()){
           ss+=S1[i];
           i++;
    }
    while(j<S2.size()){
           ss+=S2[j];
           j++;
    }
    return ss;
    
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.