SDE & MLE Prep

1768. Merge Strings Alternately

Problem

Interleave word1 and word2 letter by letter, starting with word1; when one runs out, append the rest of the other.

Example: word1 = "ab", word2 = "pqrs" → "apbqrs"

Take one character from each word in turn; when one runs out, append the rest of the other.

Complexity: O(n + m).

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        return "".join(a + b for a, b in itertools.zip_longest(word1, word2, fillvalue=""))