Given two strings, merge them in an alternate manner such that the first character of the result comes from the first string, the second from the second string, and so on. If one string gets exhausted before the other, append the remaining characters of the other string to the end of the result.
Examples:
Input : s1 = "abcde", s2 = "xyz"
Output: "axbyczde"
Explanation: Characters are picked alternately from both strings, and after the second string ends, the remaining"de"from the firstsecond string is appended.
Input : s1 = "hello", s2 = "geeks"
Output : hgeelelkos
Explanation: Characters are picked alternately from both strings until both strings are fully exhausted with no remaining characters left.
Using Two Pointer – O(m + n) Time O(m + n) Space
The idea is to merge two strings in an alternate fashion using a single loop. We iterate from index
0to the maximum length of both strings. At each index, we first check if the current index exists in the first string and append its character to the result. Then we do the same for the second string. This ensures characters are added alternately. If one string is shorter, the remaining characters of the longer string are automatically appended because of the loop condition.
Let us understand with an example:
Input: s1 = "geeks", s2 = "forgeeks"
Start picking characters alternately from both strings:
- Take 'g' from s1 -> result = "g"
- Take 'f' from s2 -> result = "gf"
- Take 'e' from s1 -> result = "gfe"
- Take 'o' from s2 -> result = "gfeo"
- Take 'e' from s1 -> result = "gfeoe"
- Take 'r' from s2 -> result = "gfeoer"
- Take 'k' from s1 -> result = "gfeoerk"
- Take 'g' from s2 -> result = "gfeoerkg"
- Take 's' from s1 -> result = "gfeoerkgs"
Now s1 is exhausted. Append remaining characters of s2 ("eeks"):
Final result = "gfeoerkgseeks"
#include <bits/stdc++.h>
using namespace std;
// Function to alternatively merge two strings
string merge(string &s1, string &s2) {
// To store the final merged string
string res = "";
// Loop runs till both strings are fully traversed
for (int i = 0; i < s1.length() || i < s2.length(); i++) {
// If current index exists in first string
if (i < s1.length())
res += s1[i];
// If current index exists in second string
if (i < s2.length())
res += s2[i];
}
return res;
}
// Driver code
int main() {
string s1 = "geeks";
string s2 = "forgeeks";
cout << merge(s1, s2);
return 0;
}
#include <stdio.h>
#include <string.h>
// Function to alternatively merge two strings
void merge(char *s1, char *s2, char *res) {
int i = 0;
while (i < strlen(s1) || i < strlen(s2)) {
if (i < strlen(s1))
res[i] = s1[i];
if (i < strlen(s2))
res[strlen(s1) + i] = s2[i];
i++;
}
res[strlen(s1) + strlen(s2)] = '\0';
}
// Driver code
int main() {
char s1[] = "geeks";
char s2[] = "forgeeks";
char res[100] = {0};
merge(s1, s2, res);
printf("%s", res);
return 0;
}
// Function to alternatively merge two strings
public class GfG {
public static String merge(String s1, String s2) {
// To store the final merged string
String res = "";
// Loop runs till both strings are fully traversed
for (int i = 0; i < s1.length() || i < s2.length(); i++) {
// If current index exists in first string
if (i < s1.length())
res += s1.charAt(i);
// If current index exists in second string
if (i < s2.length())
res += s2.charAt(i);
}
return res;
}
// Driver code
public static void main(String[] args) {
String s1 = "geeks";
String s2 = "forgeeks";
System.out.println(merge(s1, s2));
}
}
"""
Function to alternatively merge two strings
"""
def merge(s1, s2):
# To store the final merged string
res = ""
# Loop runs till both strings are fully traversed
for i in range(max(len(s1), len(s2))):
# If current index exists in first string
if i < len(s1):
res += s1[i]
# If current index exists in second string
if i < len(s2):
res += s2[i]
return res
# Driver code
s1 = "geeks"
s2 = "forgeeks"
print(merge(s1, s2))
using System;
// Function to alternatively merge two strings
public class GfG
{
public static string merge(string s1, string s2)
{
// To store the final merged string
string res = "";
// Loop runs till both strings are fully traversed
for (int i = 0; i < s1.Length || i < s2.Length; i++)
{
// If current index exists in first string
if (i < s1.Length)
res += s1[i];
// If current index exists in second string
if (i < s2.Length)
res += s2[i];
}
return res;
}
// Driver code
public static void Main()
{
string s1 = "geeks";
string s2 = "forgeeks";
Console.WriteLine(merge(s1, s2));
}
}
// Function to alternatively merge two strings
function merge(s1, s2) {
// To store the final merged string
let res = "";
// Loop runs till both strings are fully traversed
for (let i = 0; i < s1.length || i < s2.length; i++) {
// If current index exists in first string
if (i < s1.length)
res += s1[i];
// If current index exists in second string
if (i < s2.length)
res += s2[i];
}
return res;
}
// Driver code
let s1 = "geeks";
let s2 = "forgeeks";
console.log(merge(s1, s2));
Output
gfeoerkgseeks
Time Complexity: O(max(m, n)), where m and n are the lengths of string1 and string2 respectively, since we traverse up to the maximum length of both strings once.
Auxiliary Space: O(m + n), since a new result string is created to store all characters from both strings.