- Interview Questions
- /
- Problems
- /
- Merge Strings Alternately
Merge Strings Alternately
Interleave two strings one character at a time, then tack on whatever is left of the longer one. A quick check that you can walk two sequences of different lengths cleanly. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given two strings word1 and word2. Build a new string by taking characters from them in turns: the first character of word1, then the first of word2, then the second of word1, then the second of word2, and so on.
If one string runs out before the other, append the rest of the longer string to the end unchanged. Return the merged string.
Example 1
- Input
- word1 = "cat", word2 = "dog"
- Output
- "cdaotg"
c, d, a, o, t, g.
Example 2
- Input
- word1 = "hi", word2 = "there"
- Output
- "htihere"
After h, t, i, h the first word is used up, so "ere" is appended.
Example 3
- Input
- word1 = "abcd", word2 = "z"
- Output
- "azbcd"
Constraints
- 1 ≤ word1.length, word2.length ≤ 10⁴
- Both strings contain only lowercase and uppercase English letters.
- The two strings may have different lengths.
Practice
Runs 12 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Merge Strings Alternately in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Merge Strings Alternately
Pattern: Two pointers over two sequences
Walk both strings with a shared index i. At each step, take word1[i] if it exists, then word2[i] if it exists. Running i up to the length of the longer string means the leftover tail is handled by the same loop: once the shorter string is exhausted, its check simply fails and only the longer string contributes.
The one performance detail is how you build the result. Collect characters in a list (or array) and join once at the end, instead of growing a string inside the loop.
Approach 1: Loop to the shorter length, then append the tail
Interleave for min(len1, len2) steps, then append word1[min:] and word2[min:]. One of those slices is empty. Correct and clear, but it is two pieces of logic where one would do.
Time O(n + m) · Space O(n + m)
Approach 2: Single loop to the longer length
For i from 0 to max(len1, len2) - 1:
- If
i < len1, appendword1[i]. - If
i < len2, appendword2[i].
Join the collected characters at the end.
Time O(n + m) · Space O(n + m)
| Approach | Time | Space |
|---|---|---|
| Loop to the shorter length, then append the tail | O(n + m) | O(n + m) |
| Single loop to the longer length | O(n + m) | O(n + m) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Merge Strings Alternately solution in Python
def merge_alternately(word1: str, word2: str) -> str:
out = []
for i in range(max(len(word1), len(word2))):
if i < len(word1):
out.append(word1[i])
if i < len(word2):
out.append(word2[i])
return "".join(out)Merge Strings Alternately solution in JavaScript
function mergeAlternately(word1, word2) {
const out = [];
const n = Math.max(word1.length, word2.length);
for (let i = 0; i < n; i++) {
if (i < word1.length) out.push(word1[i]);
if (i < word2.length) out.push(word2[i]);
}
return out.join('');
}Common mistakes
- Stopping at the shorter length and forgetting the leftover characters.
- Taking `word2` first, which flips the order of every pair.
- Indexing past the end of the shorter string without a bounds check (an exception in Python, `undefined` concatenated as text in JavaScript).
- Building the result with repeated string concatenation in a language where that copies the whole string each time.
What interviewers look for
This is a warm-up. Say the plan in one sentence and pick the single-loop version so there is no separate tail case to get wrong.
Mention why you collect into a list and join: strings are immutable in Python and Java, so repeated += can turn an O(n) loop into O(n²). That small remark signals you think about cost even on easy problems.
Follow-up questions
How would you merge k strings round-robin?
Loop `i` up to the longest length and, for each `i`, visit the strings in order, appending `s[i]` when it exists. Total work is the sum of the lengths plus k times the longest length for the bounds checks; a queue of still-active strings avoids revisiting finished ones.
What if the inputs were streams you can only read once?
Read one character from each stream in turn, and when one stream ends, drain the other. You never need more than one character of buffer per stream.
How would you undo the merge if you know both lengths?
For the first `2 * min(n, m)` characters, even positions belong to word1 and odd positions to word2. Everything after that belongs to whichever word was longer.
Companies that ask Merge Strings Alternately
Merge Strings Alternately is tagged by 102 companies in our interview dataset. The score shows how often it comes up at each company.
- Encora100%
- Wisetech Global99%
- Mphasis99%
- Sabre95%
- Micron Technology93%
- Lumentum86%
- Angi83%
- Optym83%
- Allegro83%
- Ss C Technologies83%
- Getyourguide82%
- State Farm82%
- Tokyo Electron82%
- Turnberry Solutions81%
- Testlio80%
- Blue Yonder80%
- Ford Motor79%
- Zego79%
- Springworks Therapeutics78%
- Vistaprint78%
- Hashicorp77%
- Dicks Sporting Goods77%
- Biomérieux76%
- Argyle75%
and 78 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required