Merge Strings Alternately (LeetCode 1768): Solution and Explanation
Interleave two strings character by character, starting with word1, and append whatever is left of the longer string once the shorter one runs out.
Intuition
Picture the two words written one above the other. Column i holds word1[i] on top and word2[i] underneath, and the merged string reads the columns left to right, top before bottom.
When one word is shorter, its columns simply end. The remaining columns have only one character each, so reading them in order appends the leftover tail with no special case.
That means a single index i is enough: keep going while i is inside at least one word, and at each step append whichever of word1[i] and word2[i] exist.
Approach: One shared index
- Create an empty output buffer and set
i = 0. - While
i < len(word1)ori < len(word2): ifi < len(word1)appendword1[i]; ifi < len(word2)appendword2[i]; then incrementi. - Join the buffer and return it.
Step-by-step example
word1 = "ab", word2 = "pqrs"
- i = 0: append
afrom word1, thenpfrom word2. Outputap. - i = 1: append
b, thenq. Outputapbq. - i = 2: word1 has no index 2, so only
rfrom word2 is appended. Outputapbqr. - i = 3: only
sfrom word2. Outputapbqrs. - i = 4 is past both words, so the loop ends and the answer is
"apbqrs".
Code: Python, Java, C++
1class Solution:
2 def mergeAlternately(self, word1: str, word2: str) -> str:
3 out = []
4 i = 0
5 while i < len(word1) or i < len(word2):
6 if i < len(word1):
7 out.append(word1[i])
8 if i < len(word2):
9 out.append(word2[i])
10 i += 1
11 return ''.join(out)1class Solution {
2 public String mergeAlternately(String word1, String word2) {
3 StringBuilder out = new StringBuilder();
4 int i = 0;
5 while (i < word1.length() || i < word2.length()) {
6 if (i < word1.length()) {
7 out.append(word1.charAt(i));
8 }
9 if (i < word2.length()) {
10 out.append(word2.charAt(i));
11 }
12 i++;
13 }
14 return out.toString();
15 }
16}1class Solution {
2public:
3 string mergeAlternately(string word1, string word2) {
4 string out;
5 size_t i = 0;
6 while (i < word1.size() || i < word2.size()) {
7 if (i < word1.size()) {
8 out += word1[i];
9 }
10 if (i < word2.size()) {
11 out += word2[i];
12 }
13 i++;
14 }
15 return out;
16 }
17};Time and space complexity
O(m + n)
The loop runs max(m, n) times and appends each of the m + n characters exactly once.
O(m + n)
The output holds all m + n characters. Apart from it, only the index is stored.
Other approaches
Two pointers (time O(m + n), space O(m + n))
Keep separate indices into each word and alternate while both have characters, then append the rest of whichever word is left with a slice. Same cost, slightly more code, but it makes the tail step explicit.
zip_longest (time O(m + n), space O(m + n))
In Python, ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue='')) does the same thing in one line. Good to mention, but interviewers usually want the loop.
Common mistakes
- Looping only to
min(m, n)and forgetting to append the tail of the longer word. - Using
andinstead oforin the loop condition, which stops as soon as the shorter word ends. - Reading
word1[i]orword2[i]without the bounds check, which throws once one word is exhausted. - Building the result with repeated string concatenation in a language with immutable strings; use a list or builder.
Frequently asked questions
Which word goes first?
Always word1. Each round appends word1[i] before word2[i], so the merged string starts with the first character of word1.
What happens when the words have different lengths?
Once the shorter word runs out, its bounds check fails on every later round, so only the longer word's characters are appended. That is exactly the leftover tail the problem asks for.
How long is the result?
Always len(word1) + len(word2), because every character from both words is appended once.
What is the time and space complexity?
O(m + n) time and O(m + n) space for the output.