Merge Strings Alternately - Problem
You are given two strings word1 and word2. Your task is to merge these strings by alternating characters, starting with the first character of word1.
The merging process works as follows:
- Take the first character from
word1, then the first character fromword2 - Continue alternating: second character from
word1, second character fromword2, and so on - If one string is longer than the other, append the remaining characters to the end of the merged result
Example: If word1 = "abc" and word2 = "pqr", the result should be "apbqcr" (a→p→b→q→c→r).
Return the merged string as your final answer.
Input & Output
example_1.py — Basic Case
$
Input:
word1 = "abc", word2 = "pqr"
›
Output:
"apbqcr"
💡 Note:
The merged string is formed by alternating characters: a (from word1) + p (from word2) + b (from word1) + q (from word2) + c (from word1) + r (from word2) = "apbqcr"
example_2.py — Different Lengths
$
Input:
word1 = "ab", word2 = "pqrs"
›
Output:
"apbqrs"
💡 Note:
After alternating a-p-b-q, word1 is exhausted, so we append the remaining characters "rs" from word2 to get "apbqrs"
example_3.py — First String Longer
$
Input:
word1 = "abcd", word2 = "pq"
›
Output:
"apbqcd"
💡 Note:
After alternating a-p-b-q, word2 is exhausted, so we append the remaining characters "cd" from word1 to get "apbqcd"
Constraints
- 1 ≤ word1.length, word2.length ≤ 100
- word1 and word2 consist of lowercase English letters only
- At least one of the strings will be non-empty
Visualization
Tap to expand
Understanding the Visualization
1
Setup Two Decks
Place word1 (blue deck) and word2 (red deck) side by side, with a pointer at the top of each deck
2
Alternate Picks
Start with blue deck (word1), pick one card, then switch to red deck (word2), pick one card, repeat
3
Handle Remaining Cards
When one deck runs out, simply take all remaining cards from the other deck and add them to your result pile
Key Takeaway
🎯 Key Insight: By using two pointers and alternating between strings, we can merge them efficiently in a single pass without complex index calculations or multiple string traversals.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code