Intuition
break down problem in 3 parts
- null check
- merge strings alternatively starting word1
- appending the rest to the end of the shorter string
the core logic: inside of for loop of word1 append ith element of word1 and word2 if i < length of word2
check if length of word2 is greater than length of word1 and if so append the rest of word2 at the end of res
Take away
using += in a string is actually inefficient compared to appending to an array so it is better to use two pointer and adding to a list and combining them back to create a list
Optimal Solution
My initial solution
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
# null check
if len(word1) == 0:
return word2
elif len(word2) == 0:
return word1
# merging alternately starting word1
res = ""
for i in range(len(word1)):
res += word1[i]
if i < len(word2):
res += word2[i]
# appending the rest to the end of shorter string
if len(word2) > len(word1):
res += word2[len(word1):]
Optimal Solution
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
i,j = 0,0
res = []
while i < len(word1) and j < len(word2):
res.append(word1[i])
res.append(word2[j])
i += 1
j += 1
res.append(word1[i:])
res.append(word2[j:])
return "".join(res)
Time Complexity
Time Complexity O(N+M)
Space Complexity O(N+M)