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.
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
# create an empty list to store merged characters
merged = []
for i, j in zip(word1, word2): # loop to iterate each characters in word1 and word2
merged.append(i + j) # append each pair of the characters
merged.append(word1[len(word2):]) # in case word1 is longer than word2
merged.append(word2[len(word1):]) # and vice versa
return "".join(merged) # join each elment in the merged list
Time complexity: O(n + m)
Space complexity: O(n + m)