LeetCode #1768 Easy

Merge Strings Alternately

Merge Strings Alternately: build a string by taking characters alternately from word1 and word2, starting with word1. If one runs out, append the rest of the other.

Constraints
  • 1 <= word1.length, word2.length <= 100
  • word1 and word2 consist of lowercase English letters.
stringtwo-pointers
Open on LeetCode ↗
02

Intuition

Two pointers advance in lockstep, taking one character from each word per round. The moment a pointer passes the end of its word, that side simply stops contributing — the other side keeps going until it too is exhausted. A single loop that runs while either index is still valid handles both phases without a special case.

How to spot this pattern

Interleaving two sequences with a graceful tail is the merge step you already know from merge sort, and from merging two sorted linked lists. The reusable trick is guarding each append with its own bounds check so one loop covers both the alternating phase and the leftover phase.

03

Approach

Try it first

Before reading on: what should happen on the round after the shorter word runs out? See whether you can write a single loop condition that keeps working through that transition instead of branching into a second phase. Aim for O(n + m).

1

One loop that survives the shorter word ending

The natural instinct is two phases: alternate while both words have characters, then append the leftover tail. That works, but it can be collapsed. Loop while i < len(word1) or j < len(word2), and inside, append word1[i] only if i is still in range, then word2[j] only if j is in range. Once the shorter word is exhausted, its guard simply stops firing and the loop degenerates into copying the rest of the longer word — no separate tail-handling code is needed.

2

Order within each round is what defines the result

The problem specifies starting with word1, so within a single iteration the character from word1 must be appended before the one from word2. Getting this backwards produces a string that is the right length with the right characters in the wrong interleaving, which is easy to miss in testing when both words are the same length. Increment each pointer immediately after using it so the two never drift out of sync.

3

Building the result efficiently

Repeated string concatenation with += creates a new string on every step, giving O(n²) behaviour in the worst case. Append characters to a list and "".join() once at the end — the same reason Java uses StringBuilder and C++ reserves capacity. The final cost is O(n + m) time and O(n + m) space, which is optimal since the output itself has that length.

04

Solution & live demo

1class Solution:
2 def mergeAlternately(self, word1, word2):
3 merged = []
4 i = j = 0
5 while i < len(word1) or j < len(word2):
6 if i < len(word1):
7 merged.append(word1[i])
8 i += 1
9 if j < len(word2):
10 merged.append(word2[j])
11 j += 1
12 return "".join(merged)
05

Common pitfalls

Looping while both are in range

✗ Wrong
while i < len(word1) and j < len(word2):
✓ Right
while i < len(word1) or j < len(word2):

With and, the loop stops as soon as the shorter word ends and the remainder of the longer word is silently dropped — "ab" + "pqrs" returns "apbq" instead of "apbqrs". Use or and guard each append.

Appending word2 before word1

✗ Wrong
merged.append(word2[j])
merged.append(word1[i])
✓ Right
merged.append(word1[i])
merged.append(word2[j])

The problem states the merge starts with word1. Reversing the order yields "paqbrc" instead of "apbqcr" — same characters, wrong answer, and invisible if you only test with identical words.

Concatenating strings in the loop

✗ Wrong
merged = ""
merged += word1[i]
✓ Right
merged = []
merged.append(word1[i])
# ...
return "".join(merged)

Python strings are immutable, so each += copies the whole accumulated string, making the loop O(n²). Collect in a list and join once.

06

Edge cases

Equal lengths, e.g. "abc" and "pqr"

Both pointers finish together and the result is a clean alternation, "apbqcr".

word1 shorter, e.g. "ab" and "pqrs"

After two rounds only word2's guard fires, appending "rs" to give "apbqrs".

word2 shorter, e.g. "abcd" and "pq"

The remaining "cd" is appended, giving "apbqcd".

One word empty

Only the non-empty word's guard ever fires, so the other string is returned as-is.

Single characters

One round appends both and the loop ends.

07

Complexity

Time
O(n + m)
Space
O(n + m)
Every character is appended exactly once; the space is the output itself.