LeetCode #1768 Easy

Merge Strings Alternately

Merge Strings Alternately is LeetCode 1768 (Easy). Build a new string from word1 and word2 by taking letters in turn, starting with word1. When one word runs out, add the rest of the other word to the end.

Both words hold 1 to 100 lowercase letters.

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

Intuition

Round i takes word1[i] and then word2[i]: both words are read at the same position. So one index i, run up to the length of the longer word, is enough, with a bounds check before each take.

  • While both words have letters: both checks pass and the letters alternate.
  • After the shorter word ends: its check fails, so only the longer word adds letters. That is exactly the leftover tail, with no separate step to append it.

Collect the letters in a list and join them once at the end.

How to spot this pattern

Taking alternate characters of two strings, with a tail when one runs out, is the same loop shape as zipping two lists of different lengths. Guard each take with its own bounds check and the tail takes care of itself.

03

Approach

Try it first

Before reading on, decide what your loop should do in a round where one word has already run out. Try to write one loop condition that keeps working through that moment instead of a second loop for the tail. Aim for O(n + m).

1

Loop up to the longer length

Run i from 0 to max(len(word1), len(word2)) − 1. Every letter of the longer word sits at an index below its length, so this range reaches all of them.

2

Take from word1 first

If i < len(word1), append word1[i]. It goes before word2[i] because every round of the merge starts with the first word, as the problem asks.

3

Then take from word2

If i < len(word2), append word2[i]. The two checks are separate, so a word that has run out is simply skipped while the other keeps adding letters.

4

Join once at the end

Return "".join(merged). Strings in Python and Java can't be changed in place, so += in a loop copies the whole string each time; a list or StringBuilder grows without copying.

04

Merge Strings Alternately solution in Python | C++ | Java

▶1class Solution:
▶2 def mergeAlternately(self, word1, word2):
▶3 merged = []
▶4 for i in range(max(len(word1), len(word2))):
▶5 if i < len(word1):
▶6 merged.append(word1[i])
▶7 if i < len(word2):
▶8 merged.append(word2[i])
▶9 return "".join(merged)
word1abcword2pqrmerged3 rounds, 6 empty slots
len(word1)3
len(word2)3
rounds3the longer length
The loop runs 3 rounds, the length of the longer word, so it reaches every letter. The merged string will hold all 6 letters, one slot each.
word1abcword2pqri = 0i = 0mergedatake 'a' from word1 → slot 0
i0
word1[0]"a"
merged"a"
Round 0 starts with word1. Index 0 is inside word1, so a goes into slot 0.
word1abcword2pqri = 0i = 0mergedaptake 'p' from word2 → slot 1
i0
word2[0]"p"
merged"ap"
Then word2 gets its turn in round 0: p goes into slot 1.
word1abcword2pqri = 1i = 1mergedapbtake 'b' from word1 → slot 2
i1
word1[1]"b"
merged"apb"
Round 1 starts with word1. Index 1 is inside word1, so b goes into slot 2.
word1abcword2pqri = 1i = 1mergedapbqtake 'q' from word2 → slot 3
i1
word2[1]"q"
merged"apbq"
Then word2 gets its turn in round 1: q goes into slot 3.
word1abcword2pqri = 2i = 2mergedapbqctake 'c' from word1 → slot 4
i2
word1[2]"c"
merged"apbqc"
Round 2 starts with word1. Index 2 is inside word1, so c goes into slot 4.
word1abcword2pqri = 2i = 2mergedapbqcrtake 'r' from word2 → slot 5
i2
word2[2]"r"
merged"apbqcr"
Then word2 gets its turn in round 2: r goes into slot 5.
word1abcword2pqrmergedapbqcrreturn "apbqcr"
result"apbqcr"
Every slot is filled, so join the list once: "apbqcr". Equal lengths mean no round was skipped and there is no tail.
05

Common pitfalls

Stopping when the shorter word ends

✗ Wrong
while i < len(word1) and j < len(word2):
    merged.append(word1[i])
    merged.append(word2[j])
    i += 1
    j += 1
✓ Right
for i in range(max(len(word1), len(word2))):
    if i < len(word1):
        merged.append(word1[i])
    if i < len(word2):
        merged.append(word2[i])

With and, the loop ends as soon as either word runs out. For "ab" and "pqrs" it returns "apbq" and loses "rs". Two-pointer versions must append both leftover tails after the loop; the single loop above needs no extra step.

06

Complexity

Time
O(n + m)
Space
O(n + m)
n and m are the two lengths. Each letter is appended once and each round does two bounds checks. The space is the output string itself; apart from it only the index is stored.
07

Merge Strings Alternately FAQ

Can Python's zip_longest do this in one line?

Yes: "".join(a + b for a, b in zip_longest(word1, word2, fillvalue="")), with zip_longest from itertools. The fillvalue="" stands in for the letters the shorter word lacks, so the tail of the longer word is kept.

Do I need two pointers?

Two pointers i and j work, but here they always hold the same value, because both words move forward once per round. One index says the same thing with less to track. Separate pointers matter when the two inputs move at different speeds, as when merging two sorted arrays.

How would you merge k strings alternately?

Loop i up to the longest length and, inside, go through the strings in order, appending s[i] whenever i < len(s). The work is the total number of letters plus one bounds check per string per round.