Merge Strings Alternately (LeetCode 1768): Two Pointers, Then the Tail

Merge two strings by taking characters alternately, starting with the first string. When one string runs out, append the rest of the other.

Idea

Walk both strings with one index while both have characters left, then add whatever remains of the longer one.

def mergeAlternately(word1, word2):
    out = []
    n = min(len(word1), len(word2))
    for i in range(n):
        out.append(word1[i])
        out.append(word2[i])
    out.append(word1[n:])
    out.append(word2[n:])
    return "".join(out)

Why a list

Strings are immutable in Python, so repeated += can copy the result many times. Collecting pieces in a list and joining once keeps it O(m + n).

Interview notes

It is a warm-up question, so the signal is clean code: no off-by-one on the tail, and a quick test with unequal lengths such as "ab" and "pqrs" giving "apbqrs".

If you want to rehearse explaining solutions like this under time pressure, AI coding interview helper is something I help build (disclosure: I work on Linkjob AI).