You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.

Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1 : a b c
word2 :  p p r
merged: apbqcr
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: The merged string will be merged as so:
word1 : a b
word2 :  p p r s
merged: apbqrs
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: The merged string will be merged as so:
word1 : a b c d
word2 :  p p
merged: apbqcd
Constraints:

Contents

In this approach, we will use pointers to iterate through word1 and word1, and take alternative characters to form a new string.

Implementation steps:
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 m is the length of input string word1 and n is the length of word2.
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 GitHub link for Java code