Merge Strings Alternately · Optimal Solution

Interleave one from each, then append the rest.

A messaging platform combines status updates from two partner feeds into a single blended stream — one from each, alternating. This problem works the same way at the character level: given two strings, interleave their characters one at a time, and when the shorter string runs out, append whatever remains from the longer one. O(n + m) time. O(n + m) space.


Interactive

Watch the merge build character by character


Concept

Alternate pairs, then tail

The merge has at most two phases: an interleave while both words have characters at the same index, then a tail append from whichever word is longer.

shared-index interleave

While both strings have a character at the current index, take one from word1 then one from word2. Each shared index produces exactly two result characters.

append the remaining tail

Once the shorter string is exhausted, every remaining character from the longer string is appended in order. No further alternation — just a straight copy.

stable ordering

Characters from each word maintain their original relative order. The merge interleaves positions but never rearranges characters within either source.


Algorithm

Two loops, one result

One loop handles the shared-index pairs. A second handles the leftover tail.

  1. 1

    Calculate the shared length

    Set shared = min(word1.length, word2.length). This is how many indices both words cover.

  2. 2

    Interleave shared indices

    For each index i from 0 to shared − 1, append word1[i] then word2[i] to the result.

  3. 3

    Identify the longer word

    If word1.length > shared, word1 has leftover characters. Otherwise word2 does. If equal, there is no tail.

  4. 4

    Append the tail

    Copy the remaining characters from index shared to the end of the longer word. The result is complete.


Edge Cases

Where one phase vanishes

Some inputs make the merge trivially short by eliminating an entire phase.

Equal lengths

When both words have the same length, every character participates in a shared pair. The tail phase is empty — the interleave alone produces the full result.

One character each

A single shared pair with no tail. The result is simply word1[0] followed by word2[0] — two characters, one pair, done.

Vastly unequal lengths

When one word is much shorter, most of the result comes from the tail. After one or two shared pairs, the longer word's suffix dominates the output.