21. Merge Two Strings Alternately
Given two strings, build a new string by alternating their characters and append the remainder when one string ends.
I use two pointers, one for each string, and a list to build the result. While either string still has characters, I append the next character from word1 when available, then the next character from word2 when available. This keeps the required alternating order. When one string ends, the loop continues with the remaining characters of the other string. The time complexity is O(m + n), and the auxiliary space complexity is O(m + n).
See the Code while reading this explanation.
The problem gives us two strings and asks us to create one new string. We take one character from word1, then one from word2, and repeat. If one string ends first, we append the remaining characters from the longer string. Two pointers work well because each pointer tracks the next unused character in one input string.
- What input sizes, value ranges, and edge cases should the solution handle?
- What output should be returned for empty, invalid, or duplicate input?
- Should I prioritize execution time or memory use, and may I use the standard library?
The inputs are two strings named word1 and word2. The output is one new merged string.
In the diagram, word1 is "abcde" and word2 is "pqr". The expected output is "apbqcrde".
The characters must keep their original order inside each input string. We only alternate the string from which we take the next character.
I use two integer pointers named i and j. Pointer i tracks the next unused character in word1. Pointer j tracks the next unused character in word2.
I also use a list named result. Appending characters to a Python list is efficient. After processing both strings, I join the list into one final string.
The main invariant is that result contains every character before index i in word1 and every character before index j in word2 in the required alternating order.
Set i = 0 and j = 0. Both pointers start at the first character of their strings.
Create result = []. It is empty because no characters have been processed yet.
The loop continues while i is inside word1 or j is inside word2. The or condition is important because processing must continue after one string ends.
Start with word1 = "abcde", word2 = "pqr", i = 0, j = 0, and result = [].
Step 1: i is valid. Append word1[0], which is "a". The result becomes ["a"]. Increase i to 1.
Step 2: j is valid. Append word2[0], which is "p". The result becomes ["a", "p"]. Increase j to 1.
Step 3: append word1[1], which is "b". The result becomes ["a", "p", "b"]. Increase i to 2.
Step 4: append word2[1], which is "q". The result becomes ["a", "p", "b", "q"]. Increase j to 2.
Step 5: append word1[2], which is "c". The result becomes ["a", "p", "b", "q", "c"]. Increase i to 3.
Step 6: append word2[2], which is "r". The result becomes ["a", "p", "b", "q", "c", "r"]. Increase j to 3.
Now word2 has ended, but word1 still has two characters.
Step 7: append word1[3], which is "d". The result becomes ["a", "p", "b", "q", "c", "r", "d"]. Increase i to 4.
Step 8: append word1[4], which is "e". The result becomes ["a", "p", "b", "q", "c", "r", "d", "e"]. Increase i to 5.
Both strings are now finished. Joining the list returns "apbqcrde".
During each loop iteration, the algorithm appends the next unused character from word1 when one exists. It then appends the next unused character from word2 when one exists.
This preserves the order of characters inside both strings. It also creates the required alternating order while both strings still have characters.
When one string ends, its condition becomes false. The condition for the other string can still be true, so its remaining characters are appended in order.
Therefore, every input character is added exactly once, and the returned string is correct.
The function initializes i, j, and result. The while condition uses or so the loop continues until both strings are fully processed.
The first if statement checks whether word1 still has an unused character. If it does, the code appends word1[i] and increments i.
The second if statement checks whether word2 still has an unused character. If it does, the code appends word2[j] and increments j.
Finally, "".join(result) combines the collected characters and returns the merged string.
Let m be the length of word1 and n be the length of word2. Each input character is processed once, so the time complexity is O(m + n).
The result list can hold m + n characters, so the auxiliary space complexity is O(m + n).
The same code handles an empty string, two empty strings, strings with very different lengths, and strings that each contain one character.
Use one pointer for each string and one list for the merged output. During each loop iteration, append word1[i] if i is valid, then append word2[j] if j is valid. Increment only the pointer whose character was appended. The central invariant is that result contains all characters before i in word1 and all characters before j in word2 in the correct alternating order. The loop uses or, so it continues until both strings have been completely processed.
def mergeAlternately(word1: str, word2: str) -> str:
# Start one pointer at the beginning of each string.
i = 0
j = 0
# Store the merged characters before joining them.
result = []
# Continue until both strings are fully processed.
while i < len(word1) or j < len(word2):
# Append the next character from word1 when available.
if i < len(word1):
result.append(word1[i])
i += 1
# Append the next character from word2 when available.
if j < len(word2):
result.append(word2[j])
j += 1
# Join all collected characters into the final string.
return "".join(result)
# Example from the diagram.
word1 = "abcde"
word2 = "pqr"
answer = mergeAlternately(word1, word2)
print(answer) # apbqcrdeLet m be the length of word1 and n be the length of word2. Each character from both strings is appended exactly once, so the time complexity is O(m + n). The result list grows to contain all m + n characters before they are joined, so the auxiliary space complexity is O(m + n).
This pattern is useful when two ordered inputs must be combined while preserving the order inside each input. Examples include interleaving characters, alternating records from two lists, or combining items from two small ordered streams.
This problem checks whether a candidate can coordinate two pointers, preserve the order of two inputs, and handle unequal lengths without complicated logic. It also tests careful use of loop conditions and index bounds. The interviewer wants to see correct Python code, correct pointer updates, a clear explanation of how the remainder is appended, and accurate O(m + n) time and O(m + n) auxiliary space analysis.
A common mistake is using and instead of or in the while condition. That stops the loop when the shorter string ends and loses the remainder of the longer string. Another mistake is appending word2[i] inside the word1 branch or incrementing the wrong pointer. Candidates may also forget the boundary checks and cause an IndexError. Another mistake is changing the original order of characters. It is also incorrect to claim O(1) auxiliary space because the result list grows with the total input size.
Before writing the loop, explain that i and j always point to the next unused characters and that result already contains all earlier characters in the correct order.









