LeetCode 1768, Merge Strings Alternately, is a linear traversal problem: emit one character from each input while both have characters left, then append the unused suffix from the longer string.
Clear Python solution
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
merged = []
limit = min(len(word1), len(word2))
for index in range(limit):
merged.append(word1[index])
merged.append(word2[index])
merged.append(word1[limit:])
merged.append(word2[limit:])
return "".join(merged)
Why this handles unequal lengths
The loop stops at the shorter input. At that point, exactly one suffix can be non-empty, but appending both slices is simpler and correct because appending an empty string has no effect. This avoids exception-driven control flow and makes the boundary obvious.
Complexity
The algorithm reads each input character once and creates one output character per input character: O(m + n) time and O(m + n) output space. A list plus join avoids repeatedly reallocating immutable Python strings.
Example
For word1 = "ab" and word2 = "pqrs", the loop emits apbq, then the remaining suffix is rs, producing apbqrs.
Problem reference: LeetCode 1768: Merge Strings Alternately.
Leave a Reply