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 Alternately INPUT word1 = "abc" a b c 0 1 2 word2 = "pqr" p q r 0 1 2 Two pointers: i, j i for word1, j for word2 Both start at 0 word1="abc", word2="pqr" ALGORITHM STEPS 1 Initialize result = "", i=0, j=0 2 Loop while i or j valid i < len1 OR j < len2 3 Alternate append Add word1[i], then word2[j] 4 Increment pointers i++, j++ after each add Merge Process: a + p b + q c + r --> --> "" --> "ap" --> "apbq" --> "apbqcr" Time: O(n+m) Space: O(n+m) FINAL RESULT Merged String: a p b q c r 0 1 2 3 4 5 from word1 from word2 Output: "apbqcr" [OK] Strings merged! Length = 6 (3+3) Alternating pattern: w1,w2,w1,w2... Pattern verified: a-p-b-q-c-r Key Insight: Use two pointers to traverse both strings simultaneously. At each step, append one character from each string (if available) to the result. This ensures O(n+m) time with single pass. TutorialsPoint - Merge Strings Alternately | Optimal Solution (Two Pointers)
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