Home
DSA Patterns
Two Pointers
Merge Strings Alternately
Merge Strings Alternately
Merge two strings by alternating their letters, starting with the first word, and append whatever is left of the longer word at the end.
Problem Understanding
Merge Strings Alternately (LeetCode 1768): given two strings word1 and word2, merge them by adding letters in alternating order, starting with word1. If one string is longer, append its extra letters to the end of the merged string.
Examples: "abc", "pqr" → "apbqcr"; "ab", "pqrs" → "apbqrs"; "abcd", "pq" → "apbqcd".
The Intuition: Deal the Letters Like Cards
Take one letter from the first word, one from the second, and repeat, as if dealing from two piles.
- One index for both words, since they advance together.
- Check each word's bounds before taking from it.
- Keep going to the longer length, so the longer word's tail is appended automatically.
It is the gentlest of the two pointers problems; Merge Sorted Array merges two sequences too, but chooses between them by value instead of taking turns.
Interactive Walkthrough
ONE INDEX, TWO WORDS
i = 0
word1
0
1
word2
0
1
2
3
merged
EMPTY
i
:
Length
0
Answer
:
Walk i from 0 to 3, the longer word's last index
Next
i = 0: word1[0] = 'a', append it
word1
word2
Both words share the index i. In the merged row each letter keeps its word's colour, so you can see the alternation and then the longer word's tail. Try Example 3, where word1 is longer.
Dry Run Table
Input: word1 = "ab", word2 = "pqrs".
| i | word1[i] | word2[i] | Merged |
|---|---|---|---|
| 0 | a | p | ap |
| 1 | b | q | apbq |
| 2 | (none) | r | apbqr |
| 3 | (none) | s | apbqrs |
Answer: "apbqrs".
The Solution Template
One loop to the longer length, a bounds check per word, and a single join at the end.
Merge Strings Alternately Code
1var mergeAlternately = function(word1, word2) {2 const out = [];3 for (let i = 0; i < Math.max(word1.length, word2.length); i++) {4 if (i < word1.length) {5 out.push(word1[i]);6 }7 if (i < word2.length) {8 out.push(word2[i]);9 }10 }11 return out.join('');12};
Edge Cases & Common Mistakes
- Stopping at the shorter length: the longer word's tail is lost.
- Starting with word2: the merge must begin with word1.
- One-letter words:
"a","b"gives"ab". - Forgetting the terminator in C: allocate m + n + 1 bytes and end with '\0'.
Summary
Walk one index up to the longer length, append word1[i] then word2[i] whenever they exist, and join. O(m + n) time and space.
More practice: DSA interview questions with answers · patterns cheat sheet
