1768. Merge Strings Alternately

Merge Strings Alternately - LeetCode

This is a straightforward two-pointer problem, but it is still useful for thinking about controlled iteration across two different inputs.

Intuition

The question is asking us to interleave the two strings in order.

That means we do not need anything complicated like recursion or extra indexing structures. We simply need a way to move through both words at the same time and keep taking the next available character from each.

The natural approach is to keep one pointer for word1 and one pointer for word2.

While both pointers are still within range:

  • take the next character from word1
  • take the next character from word2
  • move both pointers forward

Once one word runs out, the problem becomes even simpler. At that point we just append the remaining part of the longer word.

Implementation

I build a result list rather than concatenating directly to a string each time. Appending to a list is cleaner and more efficient, and at the end we can join everything together once.

The first while loop handles the alternating part of the merge.

After that:

  • the second loop appends any leftover characters from word1
  • the third loop appends any leftover characters from word2

The final result is "".join(res).

# 1768. Merge Strings Alternately

def mergeAlternately(word1, word2):
    i = 0
    j = 0
    res = []

    while i < len(word1) and j < len(word2):
        res.append(word1[i])
        res.append(word2[j])
        i += 1
        j += 1

    while i < len(word1):
        res.append(word1[i])
        i += 1

    while j < len(word2):
        res.append(word2[j])
        j += 1

    return "".join(res)


print(mergeAlternately("abc", "pqr"))