1768. Merge Strings Alternately - Detailed Explanation
Problem statement
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with the first string (word1). If one string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string.
Examples
Example 1:
- Input:
word1 = "abc",word2 = "pqr" - Output:
"apbqcr" - Explanation: The letters from
word1andword2are merged alternately.
First take 'a' from word1, then 'p' from word2, then 'b' from word1, and so on. The merged result is "apbqcr".
Example 2:
- Input:
word1 = "ab",word2 = "pqrs" - Output:
"apbqrs" - Explanation:
word2is longer, so after alternating"apbq", the remaining"rs"fromword2are appended at the end.
Example 3:
- Input:
word1 = "abcd",word2 = "pq" - Output:
"apbqcd" - Explanation:
word1is longer, so after alternating"apbq", the remaining"cd"fromword1are appended at the end.
Constraints:
1 <= word1.length, word2.length <= 100word1andword2consist of lowercase English letters.
This question is an instance of the two pointers pattern, where one index walks word1 and a second index walks word2 inside the same loop. Design Gurus teaches it in the Merge Strings Alternately lesson of Grokking the Microsoft Coding Interview. For a short map of the techniques that keep recurring in string and array questions, read the most common LeetCode patterns.
Hints
-
Hint 1: Try using two pointers (or indices) to iterate through both strings at the same time. On each step, take one character from
word1, then one fromword2, and so on. -
Hint 2: Determine the length of the shorter string. You can loop that many times to alternate characters, then handle any remaining part of the longer string by appending it to the result.
-
Hint 3: Consider a loop that runs while characters remain in either string. In each iteration, append a character from
word1if one is available, then append a character fromword2if one is available. That structure covers the case where one string ends before the other.
Multiple approaches
Brute force approach
The direct way to solve this question is to walk both strings character by character and build the merged string. A loop alternates between word1 and word2 until one of them runs out.
For example, append word1[0], then word2[0], then word1[1], word2[1], and so on.
Once we reach the end of one string, we append the remaining part of the other string to the result. This approach follows the problem description and is easy to implement.
How this works: We initialize an empty result, such as an empty string or list. Then we use an index i for word1 and an index j for word2.
In a loop, alternate between adding word1[i] and word2[j] to the result and incrementing the indices. When one index reaches the end of its string, break out of the alternating loop and concatenate the rest of the other string.
-
We can implement this by checking bounds at each step, or by looping a fixed number of times, such as the length of the shorter string, and then handling the leftovers. The brute force version is what the question expects: simulate the merge character by character.
-
This version is intuitive. A naive implementation can still be slow, for example when it concatenates an immutable string once per character. The constraints here are small, so even a direct implementation finishes well inside the time limit.
Optimal approach (two pointers, space efficient)
The optimal solution follows the same idea as the brute force approach, with more care about how the result is built. The difference matters most in languages where string concatenation copies the whole string.
The efficient version uses two pointers and collects characters in a buffer, such as a Python list or a Java StringBuilder. It never builds an intermediate string, so it allocates once instead of once per character.
Key idea: Use a single loop that runs until you have processed all characters from both strings. In each iteration:
-
Append the next character from
word1to the result ifword1still has characters left. -
Append the next character from
word2to the result ifword2still has characters left. -
Move the pointers forward accordingly.
A growable buffer, a list in Python or a StringBuilder in Java, lets us accumulate characters and then join or convert them once at the end. We create the final string a single time, which gives optimal time and space usage.
The same loop handles a string that ends early. The condition i < len(word1) or j < len(word2) keeps running after one index is spent, so the remaining characters of the longer string are appended after the other is exhausted.
Why it is optimal: In big-O terms this approach does the minimum necessary work. It visits each character of each string exactly once.
There are no nested loops or repeated scans, and no expensive operations outside of the single pass.
Memory usage is proportional to the length of the output, which is unavoidable because the merged string has to be stored. Besides that output buffer, the code holds only two indices.
Comparison of approaches
Both the brute force and the optimal approach ultimately have to read all characters of both input strings and produce an output string of length len(word1) + len(word2).
Therefore the time complexity of both is linear in the total length of the input. That is O(n), where n is the length of the longer string, or roughly O(m + n) for inputs of length m and n. The space complexity of both is also O(m+n), because the output string must be constructed.
The difference is in the implementation details:
-
The brute force approach, if written carelessly, concatenates a string at every step. Strings are immutable in Java and Python, so
result += charinside a loop creates many temporary strings and raises the constant cost. The idea is simple, and the practice is slightly wasteful. -
The optimal approach accumulates the result in a list or a
StringBuilder, which improves the constant factors and avoids performance problems. It refines the same algorithm rather than replacing it. The logic is identical, with no redundant copying.
In summary, both approaches run in linear time and use linear space, which is optimal for this problem given that we must output all characters.
The optimal solution is a cleaner and more efficient implementation of the brute force idea. The distinction matters most in languages where string handling needs care.
Code implementation
Python implementation
Explanation: We use two indices i and j to traverse word1 and word2. The while loop runs as long as either string has characters left.
In each iteration, we compare i against len(word1) and j against len(word2). Those two checks decide whether to take a character from word1, from word2, or from both. They also cover the shorter string. Once i reaches the end of word1, the check i < len(word1) fails and no further character comes from word1, while characters from word2 keep arriving.
We collect characters in a list and then join them at the end for efficiency. The resulting string is returned.
Alternate Python one-liner, for reference. Python's itertools.zip_longest pairs characters and fills the missing values when the lengths differ. For example:
The one-liner does the same work. It pairs the strings and uses an empty string as the filler for the shorter one. We show it to present a Pythonic option. In an interview, the two pointer loop above is clear enough.
Java implementation
Explanation: A StringBuilder builds the merged string character by character. Two indices i and j track our position in word1 and word2. The while loop continues until both strings are consumed. Inside the loop, we test for a character at word1[i] and append it, then do the same for word2[j]. That pair of tests handles uneven lengths. At the end, result.toString() returns the merged string. Prefer StringBuilder.append over string concatenation inside a Java loop, which would create many intermediate String objects.
Complexity analysis
Time complexity: Both approaches run in linear time O(n), where n is the total number of characters we need to process. More precisely, with m = len(word1) and n = len(word2), the time complexity is O(m + n). The loop reads each character of both strings once. There are no nested loops or expensive operations beyond this single pass. When word1 and word2 each hold 100 characters, the maximum allowed, the loop runs at most 100 + 100 = 200 iterations.
Space complexity: The space complexity is O(m + n) as well, and it comes from the storage for the merged output string. Combining two strings requires a new string, or a buffer, to hold the result. Apart from the output, the code keeps only a few fixed size variables, so auxiliary space is O(1). A list or a StringBuilder holds at most m+n characters before the conversion to the final string.
This is the minimum space required, because the output itself has m+n characters. No solution can beat O(m+n) space while returning every character. Both the brute force and the optimal implementation meet that bound. The optimal one also avoids excess temporary strings along the way.
Comparison: In big-O terms the two approaches match, with linear time and linear space. The difference lies in constant factors and clarity. Building the result in a Java StringBuilder or a Python list, then joining once, uses less memory than repeated concatenation in a loop. The asymptotic cost stays linear either way, which is optimal at this problem size. Each input string holds at most 100 characters, so even a plain method is fast. Efficient string building is still worth practicing, because it matters on larger inputs.
Step-by-step walkthrough with visual examples
Let us walk through an example to see how the merging works step by step. Consider Example 2 with word1 = "ab" and word2 = "pqrs":
word1: a b word2: p q r s
We will merge these strings alternately:
- Start:
i = 0,j = 0, merged ="", an empty string. - Step 1: Take
word1[i] = 'a'and append it to merged, so merged ="a". Now takeword2[j] = 'p'and append it, so merged ="ap". Incrementiandj, which givesi = 1andj = 1.- Visual: after this step we have
afrom word1 andpfrom word2 combined:merged: a p
- Visual: after this step we have
- Step 2:
i = 1,j = 1. Takeword1[1] = 'b', so merged ="apb". Then takeword2[1] = 'q', so merged ="apbq". Incrementiandj, which givesi = 2andj = 2.- Visual: merged now holds
a p b q, which is "ab" and "pq" taken alternately.
- Visual: merged now holds
- Now
i = 2, which equalslen(word1), so word1 is fully used up, whilej = 2andlen(word2) = 4. We exit the alternating loop because word1 has no more characters to alternate. - Append remainder:
word1is done, andword2still has characters left, sincej = 2and the length of word2 is 4. We append the remaining substring ofword2starting from index 2. That remaining part is"rs", the characters at indices 2 and 3. Now merged ="apbqrs". - Result: The final merged string is
"apbqrs", which matches the expected output.
Throughout this process we added letters in alternating order: a from word1, p from word2, b from word1, then q from word2. Once word1 ran out, we took the rest of word2, which is r and s. This step-by-step construction preserves the relative order of the characters inside each original word, and it places one character from each word one after the other. The merge interleaves the two sequences position by position:
word1: a b word2: p q r s merged: a p b q r s
Walk through Example 3 the same way, with word1 = "abcd" and word2 = "pq". The alternating steps produce "apbq", then the remaining "cd" from word1 is appended, which gives "apbqcd". In each case the algorithm handles the uneven lengths by appending the leftover part of the longer string at the end.
This approach works for the remaining cases too. When one string is empty, the merged result is just the other string, because the empty one contributes nothing to alternate. When both strings have the same length, the characters alternate until the two indices end at the same time.
Common mistakes and edge cases
A few mistakes come up often in this question. Here is how to avoid them:
-
Forgetting to handle leftover characters: A frequent mistake is to loop only for the length of the shorter string and skip the remaining part of the longer one. If one input is longer, those extra characters still belong at the end of the result. After the loop, check whether either index stopped short of its string, then append the remainder.
-
Off-by-one errors in loops: A single loop with a complicated condition or clever index arithmetic goes out of bounds easily. One common attempt indexes both strings from one counter with modulo logic, then breaks down when the first string ends. Two indices and straightforward loop conditions are safer, as in the solutions above. Confirm that your loop stops when it should, either when both strings are fully traversed, or at a condition inside the loop that breaks when one string ends.
-
Not truly alternating on each iteration: Some solutions toggle a flag on each pass and switch between adding from word1 and word2. Handled loosely, the flag lets two characters from the same string enter in one iteration, or introduces other logic bugs. Adding one character from each string per iteration, when available, is simpler and alternates correctly by construction. With two separate conditions in one loop, as in our approach, do not join them with
if-else. Use two independentifstatements, so a single iteration can add aword1character and aword2character when both are available. Anelsewould skip the character from the second string whenever the first string still had one. -
Inefficient string concatenation: In a language such as Java,
result = result + charinside a loop leads to O(n^2) time, because strings are immutable and every concatenation copies. In Python,result += charis cheap on short strings and slow on long ones. The fix is a buffer, aStringBuilderin Java or a list in Python, joined at the end, as we showed. The inputs here hold at most 100 characters each, so the cost is small, and the habit still matters on larger problems.
Now consider some edge cases and confirm that our solution covers them:
- Empty strings: If
word1is""andword2is not empty, the merged result should beword2, and the reverse holds whenword2is empty. Our loop handles this, because a string of length 0 simply contributes nothing while characters from the other arrive. Make sure your code does not assume non-empty strings. - One character strings: If each string has length 1, say
word1 = "x"andword2 = "y", the result should be"xy". That is the trivial case of alternating. If one string is a single character and the other is longer, sayword1 = "x"andword2 = "hello", the result should be"xhello". The logic that adds the remaining characters covers this. - Strings of equal length: Take
word1 = "abc"andword2 = "def". Here the loop alternates all characters and outputs"adbecf". Both pointers finish at the same time, and there is no remainder to append. Check that your logic works when both run out together, which the loop conditionwhile i < len1 or j < len2and the two inner checks handle cleanly. - First string longer: Take
word1 = "ABCDE"andword2 = "xy". After alternating to form"AxBy", the remainder"CDE"fromword1should be appended, which gives"AxByCDE". Our code checksi < len(word1)after the loop, or keeps going inside the loop becausejhits the end whileiis still below len1, and appends the rest. - Second string longer: Take
word1 = "hi"andword2 = "JKLMN". The result should be"hJiKLMN", where"LMN"is the leftover fromword2. Our approach appends that remainder.
Thinking through these cases, empty, unequal lengths, and equal lengths, covers every situation. The provided solution is robust against all these edge cases.
Alternative variations
This problem is a specific instance of merging or interleaving sequences. Interviewers may vary it or relate it to similar scenarios:
-
Merge more than two strings: A variation could involve three or more strings to merge in alternating, round-robin order. The concept is similar, but you cycle through the strings and take one character from each in turn. This generalizes the alternating merge. For example, merging "aa", "bbb", and "cccc" in cyclic order yields "abcabcbcc". The first two rounds take one character from each string, the third round skips the exhausted "aa", and the final round draws only from "cccc". The logic extends by looping until all strings are exhausted, taking from each one that still has a character in every cycle.
-
Zigzag iterator, two or k lists: Instead of strings, you might be asked to alternate elements from two arrays or linked lists. LeetCode has a problem called Zigzag Iterator (Problem 281), where two lists are given and the goal is to output their elements alternately. For example, the input lists
[1,2]and[3,4,5,6]should produce the output sequence[1,3,2,4,5,6]. A follow-up asks you to extend the approach toklists in a cyclic fashion. That solution uses a queue or index cycling, and the idea of taking turns from each list is analogous to this string problem. -
Interleaving string check: Another related problem is LeetCode 97: Interleaving String, which does not ask you to merge the strings but to check whether a given third string is an interleaving, or shuffle merge, of two other strings. It asks whether you can form the third string by alternating characters from the first two, not strictly every other character, but maintaining the order of characters from each. The problem states: given
s1,s2, ands3, determine whethers3is formed by an interleaving ofs1ands2. That is a harder problem, usually solved with dynamic programming, and conceptually related to merging strings. -
Merging linked lists alternately: You might encounter a linked list variation where you have two linked lists and are asked to weave them together by nodes. Nodes from each list then alternate in the resulting list. The approach is similar: take a node from list1, then one from list2, and so on, adjusting pointers as you go. This is a common operation when manipulating lists.
-
Merge two sorted lists versus alternate merge: Note the difference between this problem and merging two sorted lists, as in the classic LeetCode 21. When merging sorted lists, you choose elements by value to maintain sorted order. In an alternating merge, our problem, you ignore values and strictly take turns. The problem we solved is simpler, because you never compare elements, you only alternate them. Both are good to practice, because they involve manipulating two sequences at once. For further practice, try LeetCode 21: Merge Two Sorted Lists, another fundamental merging problem.
Related problems for practice:
- LeetCode 281: Zigzag Iterator, which asks you to implement an iterator that outputs elements from two or more lists in alternating order.
- LeetCode 97: Interleaving String, which gives three strings and asks whether the third is an interleaving of the first two. It is more advanced and involves dynamic programming.
- LeetCode 21: Merge Two Sorted Lists, which merges two linked lists by value. It is a different kind of merge, and good for understanding how to handle two data streams.
- LeetCode 1669: Merge In Between Linked Lists, a linked list problem where a portion of one list is merged into another. It does not alternate, but it exercises the merging concept.
Each of these problems touches on combining two sequences or checking combinations, which helps reinforce traversal with multiple pointers and careful condition handling.
Two more questions from the same array and string group are Reverse Words in a String and Product of Array Except Self. Both reward the same index discipline that this merge needs. The two pointers pattern and the other techniques that recur across these questions are taught in Grokking the Coding Interview.
Practicing such problems builds a strong intuition for managing multiple pointers at once, which is a common requirement in coding interview questions.

GET YOUR FREE
Coding Questions Catalog

$99

$197

$72