Merge Strings Alternately
Table of Contents + −
Merge Strings Alternately is a warm-up question, but it is a great test of clean pointer handling. You take one character from the first string, then one from the second, then back to the first. The tricky part is what happens when one string is longer than the other. Handle that and you are done.
🎯 The Problem
You get two strings. You weave them together one character at a time. The word for this is interleave. To interleave means to slot the items of one list between the items of another, turn by turn.
The rules:
- Take the first character of string one, then the first of string two.
- Then the second of string one, then the second of string two. Keep going.
- If one string is longer, attach its leftover tail at the end.
- So
"ab"and"pqrs"becomes"apbqrs".
Input: word1 = "abc", word2 = "pqr"Output: "apbqcr"
Explanation: word1: a b c word2: p q r merged: a p b q c rHere is the weave shown as the two strings feeding the answer in turn.
🐢 Approach 1: Loop To Shorter Length, Then Append (Brute Force)
The idea in one line: weave up to the shorter length, then attach the leftover tail.
The idea:
- Loop only up to the length of the shorter string.
- In each step, add one character from each string.
- After the loop, one string may still have characters left.
- Attach that whole leftover part at the end.
How it works:
- Find the shorter length first.
- Alternate inside that loop.
- A second step copies the rest of the longer string.
Why it is weak:
- It splits into two pieces of logic. The weave, then the append.
- The leftover step is easy to forget or get wrong.
- It still works and is O(n), but it reads less cleanly than one loop.
Here is the two-phase code for that idea:
def merge_alternately(word1, word2): result = [] limit = min(len(word1), len(word2))
for i in range(limit): result.append(word1[i]) result.append(word2[i])
result.append(word1[limit:]) result.append(word2[limit:]) return "".join(result)⚡ Approach 2: One Loop With Two Pointers (Best)
The idea in one line: keep one pointer per string and loop while either one still has characters. A pointer is just an index that says which character you are looking at.
The idea:
- Use two pointers, one for each string.
- Loop while either pointer still has characters left.
- Check each pointer on its own each turn.
How it works:
- If the first pointer is inside its string, add that character and move it forward.
- Then do the same for the second string.
- When one string runs out, its check fails, and only the other keeps adding.
Why it is fast:
- The leftover tail is handled for free. No separate append step.
- Each character is touched once, so time is O(n).
- A string builder keeps adding characters fast, instead of making a new string each time.
Steps to Solve
- Start two pointers,
iandj, both at zero. - Create an empty builder to collect characters.
- Loop while
iis insideword1orjis insideword2. - If
iis still insideword1, addword1[i]and moveiforward. - If
jis still insideword2, addword2[j]and movejforward. - When both pointers are past their strings, stop and return the built string.
Here is the loop weaving "abc" and "pqr". Each turn takes one character from each string while it still has one left.
This Python version collects characters in a list, then joins them at the end.
def merge_alternately(word1, word2): i, j = 0, 0 result = []
while i < len(word1) or j < len(word2): if i < len(word1): # take from word1 if any left result.append(word1[i]) i += 1 if j < len(word2): # take from word2 if any left result.append(word2[j]) j += 1
return "".join(result)
print(merge_alternately("abc", "pqr"))The output of the above code will be:
apbqcrLet us walk through the Python version line by line. We start both pointers i and j at zero. We use a list called result to collect characters. Building a string by adding one character at a time can be slow, so we gather into a list and join once at the end.
The while loop runs while i is inside word1 or j is inside word2. The or is the key. The loop keeps going as long as either string still has characters. So even when one string is finished, the other keeps feeding.
Inside, the first if i < len(word1) checks if the first string still has a character at index i. If yes, we append it and step i forward. The second if j < len(word2) does the same for the second string. Because each check stands on its own, the moment one string runs out its check fails and is skipped. That is how the leftover tail of the longer string gets added without any extra code.
When both pointers pass the ends of their strings, the loop stops. We join the list into one string and return it.
⏱️ Time and Space Complexity
We touch every character of both strings exactly once. So the time is O(m + n), where m and n are the two lengths. We build an answer that holds all those characters, so the space is O(m + n) as well. You cannot do better, since you must read and place every character at least once.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Loop to shorter length, then append rest | O(m + n) | O(m + n) |
| One loop with two pointers | O(m + n) | O(m + n) |
Tip
The “or” in the loop condition is what makes this clean. It keeps running while either string has characters left, so the longer string’s tail is added with no extra logic.
🧩 Key Takeaways
- ✅ Use two pointers and take one character from each string per turn.
- ✅ Loop while either pointer still has characters, using “or” not “and”.
- ✅ Check each pointer on its own, so the longer string’s leftover tail is added for free.
- ✅ Use a string builder or a list, so appending characters stays fast.
- ✅ The whole thing runs in O(m + n) time and space.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does it mean to merge two strings alternately?
Why: You weave one character from each string in turn, then attach the longer string's leftover tail.
- 2
Why does the loop use "or" in its condition instead of "and"?
Why: With "or", the loop keeps running while either string has characters, so the longer tail is added.
- 3
How is the leftover tail of the longer string handled in the one-loop version?
Why: Each independent if-check means once one string ends, only the other keeps appending.
- 4
What is the time complexity of merging the two strings?
Why: Every character of both strings is touched once, giving O(m + n) time.