646. Weaving Two Words Together
Two words are given. Build a new word by taking characters ALTERNATELY, starting with the first word. When one word runs out, append whatever is left of the other.
abc and pqr -> apbqcr
ab and pqrs -> apbqrs
abcd and pq -> apbqcd
## One pointer per word
i = 0, j = 0
while i < len(x) or j < len(y):
if i < len(x): emit x[i]; i += 1
if j < len(y): emit y[j]; j += 1
The loop continues while EITHER word has characters left, and each emission is guarded separately. That is what makes the leftover tail come out automatically: once one word is exhausted its guard simply stops firing, and the other keeps emitting.
## Why no separate tail loop is needed
The common first attempt runs while i < len(x) and j < len(y) and then appends the remainders
afterwards, which needs two extra loops and two more chances to get a bound wrong.
Changing the and to an or and guarding each emission removes both. Whenever a loop is
followed by "and then handle the leftovers", it is worth asking whether the condition can carry
them instead.
## The order within a round matters
Both emissions happen in the same round, first word then second. Alternating the WHOLE loop body instead, taking one character per iteration and flipping a flag, also works and is longer for no gain.
## Boundaries
Words of equal length interleave exactly. A one character word against a long one emits one character and then the entire rest of the other.
## Cost
Time O(n + m). Space O(n + m) for the output.
Constraints - `1 ≤ length of each word ≤ 100000` - both words contain only lowercase letters
Input
The first line contains the first word. The second line contains the second word.
Output
Print the woven word on one line.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.