Merge Strings Alternately
Problem
Given two strings word1 and word2, return a new string formed by merging the characters of word1 and word2 alternately. If one string is longer, append the remaining characters at the end.
- 1 ≤ word1.length, word2.length ≤ 100
- word1 and word2 consist of lowercase English letters.
Example
word1 = "abc", word2 = "pqr""apbqcr"The algorithm alternates characters from each string: 'a' from word1, 'p' from word2, 'b' from word1, 'q' from word2, 'c' from word1, and 'r' from word2. Since both strings are equal length, the merged string is simply the interleaving of characters.
Approach
Straightforward Solution
A brute-force approach would iterate over the maximum length of the two strings and append characters from each string if the index is valid. This approach is simple but requires careful boundary checks to avoid index errors.
Core Observation
The problem requires combining two sequences character-by-character in an alternating fashion, continuing until one sequence is exhausted, then appending the remainder of the other sequence.
Path to Optimal
PreviewThe key insight is to use two pointers to track positions in each string and append characters alternately while both pointers are within bounds. After one string is exhausted, append the remaining characters from the other string…
Full step-by-step walkthrough on Pro →
Optimal Approach
PreviewUse two pointers i and j initialized to zero. While both pointers are within their respective string lengths, append characters from word1[i] and word2[j], then increment both pointers…
Full step-by-step walkthrough on Pro →
Want the full reasoning chain?
Unlock the complete walkthrough, line-by-line analysis, and recall drill.
Unlock ProTime
O(n + m)
Each character from both strings is visited exactly once during the merge and append operations, where n and m are the lengths of word1 and word2 respectively.
Space
O(n + m)
The output string requires space proportional to the sum of the input strings' lengths, which is unavoidable. The auxiliary space used for the result list is also O(n + m).
Pattern Spotlight
Simulation (Two-Pointer Alternating Merge)
When merging two sequences alternately, use two pointers to track positions and append characters while both pointers are valid, then append the remainder of the longer sequence to complete the merge.
Solution
| 1 | class Solution: |
| 2 | def mergeAlternately(self, word1: str, word2: str) -> str: |
| 3 | i = j = 0 |
| 4 | res = [] |
| 5 | |
| 6 | while i < len(word1) and j < len(word2): |
| 7 | res.append(word1[i]) |
| 8 | res.append(word2[j]) |
| 9 | i += 1 |
| 10 | j += 1 |
| 11 | |
| 12 | while i < len(word1): |
| 13 | res.append(word1[i]) |
| 14 | i += 1 |
| 15 | |
| 16 | while j < len(word2): |
| 17 | res.append(word2[j]) |
| 18 | j += 1 |
| 19 | |
| 20 | return "".join(res) |
Step-by-Step Solution
Initialize Pointers and Result Container for Alternating Merge
| 3 | i = j = 0 |
| 4 | res = [] |
Objective
To set up two pointers for traversing each input string and a list to accumulate merged characters.
Key Insight
Using two pointers initialized to zero allows simultaneous traversal of both strings. A list is used to efficiently accumulate characters because string concatenation in Python is costly. This setup prepares for a clean, linear-time merge.
Interview Quick-Check
Core Logic
Two pointers track current indices in word1 and word2, enabling synchronized traversal.
Common Pitfalls & Bugs
Using string concatenation inside loops can lead to O(n²) time complexity; using a list and joining at the end is more efficient.
Merge Characters Alternately While Both Strings Have Remaining Characters
To append characters from both strings alternately while both pointers are within their string lengths.
Append Remaining Characters from the Longer String After Alternating Merge
To append any leftover characters from either word1 or word2 after the alternating merge loop completes.
Join Accumulated Characters into Final Merged String
To convert the list of merged characters into a single string for the final output.
3 more steps with full analysis available on Pro.
Line Analysis
This solution has 1 Critical line interviewers watch for.
return "".join(res)
Join all characters in the result list into a single string and return it.
Joining the list into a string produces the final merged output efficiently, completing the algorithm.
Full line-by-line criticality + rationale for all 14 lines available on Pro.
Test Your Understanding
Why is it necessary to handle the remaining characters of the longer string after the alternating merge loop?
See the answer with Pro.
Related Problems
Two Pointers pattern
Don't just read it. Drill it.
Reconstruct Merge Strings Alternately from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Merge Strings Alternately drill