Last Updated: March 29, 2026
We have two strings and need to weave them together character by character, alternating between them. Take the first character from word1, then the first from word2, then the second from word1, then the second from word2, and so on.
The twist is that the strings might not be the same length. When we run out of characters in the shorter string, we just tack on whatever is left of the longer string. So this isn't a strict "zip" operation. It's more like a zip that doesn't stop early.
The key observation: we're essentially iterating up to the length of the longer string, grabbing a character from each string when available.
1 <= word1.length, word2.length <= 100 → Both strings are very short. Even an O(n * m) approach would only be 10,000 operations. Any reasonable approach will work.word1 and word2 consist of lowercase English letters → No special characters, no empty strings to worry about.The first thing that comes to mind is to handle this in two phases. First, walk through both strings in lockstep for as long as both have characters. During this phase, we alternate: one character from word1, one from word2. Once the shorter string runs out, we just append whatever is left from the longer one.
This mirrors how you'd naturally describe the process out loud: "Take turns picking from each string until one runs out, then dump the rest."
StringBuilder or equivalent).i starting at 0.i is less than the length of both word1 and word2:word1[i] to the result.word2[i] to the result.i.word1 has remaining characters (from index i onward), append them all.word2 has remaining characters (from index i onward), append them all.This approach is already optimal in time and space, but the three separate loops are a bit verbose. Can we handle everything in a single pass?
Instead of splitting the work into "interleave phase" and "remainder phase," we can do it all in one loop. Iterate from i = 0 up to the maximum of the two lengths. At each step, if word1 still has a character at index i, add it. If word2 still has a character at index i, add it. That's it.
This naturally handles unequal lengths because the bounds check takes care of everything. When one string runs out, we just skip it and keep adding from the other. No special remainder logic needed.
The single loop iterates up to max(n, m) times. At each iteration, the bounds checks (i < len(word1) and i < len(word2)) ensure we only access valid indices. When one string is exhausted, its check fails and we simply skip it. The "remainder" is handled implicitly: once the shorter string is done, the loop keeps going and only adds characters from the longer one.
The order of the two if statements matters. We check word1 first because the problem says to start with word1. Swapping the order would produce incorrect output.
StringBuilder or equivalent).maxLen = max(len(word1), len(word2)).i from 0 to maxLen - 1:i < len(word1), append word1[i].i < len(word2), append word2[i].