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.
Example 1:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Example 2:
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Example 3:
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
word1
and word2
, and append the characters to the result list if they do.def mergeAlternately(word1: str, word2: str) -> str:
# Initialize an empty list to collect the merged characters
merged = []
# Get the length of both words
len1, len2 = len(word1), len(word2)
# Iterate through the maximum length of both words
for i in range(max(len1, len2)):
if i < len1:
merged.append(word1[i])
if i < len2:
merged.append(word2[i])
# Convert the list of characters to a string
return ''.join(merged)
The time complexity of this algorithm is O(n + m)
, where n
is the length of word1
and m
is the length of word2
. This is because we are iterating through the strings only once, and all other operations (checking index existence, appending to the list) take constant time.
mergeAlternately("abc", "pqr")
should return "apbqcr"
mergeAlternately("ab", "pqrs")
should return "apbqrs"
mergeAlternately("abcd", "pq")
should return "apbqcd"
mergeAlternately("", "pqrs")
should return "pqrs"
mergeAlternately("abcd", "")
should return "abcd"
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?