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.
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.
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.
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.
Once the shorter string is exhausted, every remaining character from the longer string is appended in order. No further alternation — just a straight copy.
Characters from each word maintain their original relative order. The merge interleaves positions but never rearranges characters within either source.
One loop handles the shared-index pairs. A second handles the leftover tail.
Set shared = min(word1.length, word2.length). This is how many indices both words cover.
For each index i from 0 to shared − 1, append word1[i] then word2[i] to the result.
If word1.length > shared, word1 has leftover characters. Otherwise word2 does. If equal, there is no tail.
Copy the remaining characters from index shared to the end of the longer word. The result is complete.
Some inputs make the merge trivially short by eliminating an entire phase.
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.
A single shared pair with no tail. The result is simply word1[0]
followed by word2[0] — two characters, one pair, done.
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.