Merge Strings Alternately
You are given two strings word1word2word1
Return the merged string.
Example 1
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1 : a b c
word2 : p p r
merged: apbqcr
Example 2
Output: "apbqrs"
Explanation: The merged string will be merged as so:
word1 : a b
word2 : p p r s
merged: apbqrs
Example 3
Output: "apbqcd"
Explanation: The merged string will be merged as so:
word1 : a b c d
word2 : p p
merged: apbqcd
Constraints:
1 <= word1.length, word2.length <= 100 andword1 consist of lowercase English letters.word2
Contents
Solution 1 - Using two pointers
In this approach, we will use pointers to iterate through word1word1
Implementation steps:
-
Create three variables
to iterate throughi ,word1 to iterate throughj , andword2 asresult to capture the result.StringBuilder -
Then, loop through characters of
andword1 , whileword2 don't go out of bounds ofi , andword1 don't go out of bounds ofj :word2-
Add character at
position from input string toith toword1 , and incrementresult .i -
Add character at
position from input string tojth toword2 , and incrementresult .j
-
Add character at
-
At the end, we may still have left with some characters either in
orword1 , if they are not equal length strings. Check ifword2 did not reach the end ofi , then add remaining characters fromword1 toword1 , and ifresult did not reach the end ofj , then add remaining characters fromword2 toword2 .result
public class MergeStringsAlternately {
static String mergeAlternately(String word1, String word2) {
int i=0;
int j=0;
StringBuilder result = new StringBuilder();
while(i<word1.length() && j<word2.length()) {
result.append(word1.charAt(i++));
result.append(word2.charAt(j++));
}
if(i<word1.length()) { // if there are any remaining characters in word1, take remaining string
result.append(word1.substring(i));
}
if(j<word2.length()) {
result.append(word2.substring(j));
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(mergeAlternately("abc", "pqr"));
System.out.println(mergeAlternately("abcd", "pq"));
System.out.println(mergeAlternately("ab", "pqrs"));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(max(m,n)) time where mword1nword2
Space complexity: O(1) if we ignore result string, otherwise O(m +n) for the result string.
Above implementations source code can be found at