Merge Strings Alternately - Problem

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.

Input & Output

Example 1 — Basic Equal Length
$ Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
💡 Note: Merge alternately: a from word1, p from word2, b from word1, q from word2, c from word1, r from word2
Example 2 — Different Lengths
$ Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
💡 Note: Merge alternately: a, p, b, q, then append remaining characters from word2: r, s
Example 3 — First String Longer
$ Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
💡 Note: Merge alternately: a, p, b, q, then append remaining characters from word1: c, d

Constraints

  • 1 ≤ word1.length, word2.length ≤ 100
  • word1 and word2 consist of lowercase English letters

Visualization

Tap to expand
Merge Strings Alternatelyword1 = "abc"abcword2 = "pqr"pqrAlternating MergeapbqcrResult StringOutput: "apbqcr"
Understanding the Visualization
1
Input
Two strings word1 and word2 of potentially different lengths
2
Merge
Alternate taking characters starting with word1
3
Append
Add remaining characters from longer string to end
Key Takeaway
🎯 Key Insight: Use two pointers to efficiently merge strings while handling different lengths
Asked in
Amazon 15 Microsoft 12 Google 8
120.0K Views
Medium Frequency
~8 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen