Merge Strings Alternately (LeetCode 1768): Solution and Explanation

Easy
Two Pointers
String

Interleave two strings character by character, starting with word1, and append whatever is left of the longer string once the shorter one runs out.

Intuition

Picture the two words written one above the other. Column i holds word1[i] on top and word2[i] underneath, and the merged string reads the columns left to right, top before bottom.

When one word is shorter, its columns simply end. The remaining columns have only one character each, so reading them in order appends the leftover tail with no special case.

That means a single index i is enough: keep going while i is inside at least one word, and at each step append whichever of word1[i] and word2[i] exist.

Approach: One shared index

  1. Create an empty output buffer and set i = 0.
  2. While i < len(word1) or i < len(word2): if i < len(word1) append word1[i]; if i < len(word2) append word2[i]; then increment i.
  3. Join the buffer and return it.

Step-by-step example

word1 = "ab", word2 = "pqrs"
  1. i = 0: append a from word1, then p from word2. Output ap.
  2. i = 1: append b, then q. Output apbq.
  3. i = 2: word1 has no index 2, so only r from word2 is appended. Output apbqr.
  4. i = 3: only s from word2. Output apbqrs.
  5. i = 4 is past both words, so the loop ends and the answer is "apbqrs".

Code: Python, Java, C++

1class Solution:
2    def mergeAlternately(self, word1: str, word2: str) -> str:
3        out = []
4        i = 0
5        while i < len(word1) or i < len(word2):
6            if i < len(word1):
7                out.append(word1[i])
8            if i < len(word2):
9                out.append(word2[i])
10            i += 1
11        return ''.join(out)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m + n)

The loop runs max(m, n) times and appends each of the m + n characters exactly once.

Space

O(m + n)

The output holds all m + n characters. Apart from it, only the index is stored.

Other approaches

Two pointers (time O(m + n), space O(m + n))

Keep separate indices into each word and alternate while both have characters, then append the rest of whichever word is left with a slice. Same cost, slightly more code, but it makes the tail step explicit.

zip_longest (time O(m + n), space O(m + n))

In Python, ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue='')) does the same thing in one line. Good to mention, but interviewers usually want the loop.

Common mistakes

  • Looping only to min(m, n) and forgetting to append the tail of the longer word.
  • Using and instead of or in the loop condition, which stops as soon as the shorter word ends.
  • Reading word1[i] or word2[i] without the bounds check, which throws once one word is exhausted.
  • Building the result with repeated string concatenation in a language with immutable strings; use a list or builder.

Frequently asked questions

Which word goes first?

Always word1. Each round appends word1[i] before word2[i], so the merged string starts with the first character of word1.

What happens when the words have different lengths?

Once the shorter word runs out, its bounds check fails on every later round, so only the longer word's characters are appended. That is exactly the leftover tail the problem asks for.

How long is the result?

Always len(word1) + len(word2), because every character from both words is appended once.

What is the time and space complexity?

O(m + n) time and O(m + n) space for the output.