You are given two strings, word1 and word2. Construct a new string by merging them in alternating order, starting with word1 — take one character from word1, then one from word2, and repeat this process.
If one string is longer than the other, append the remaining characters from the longer string to the end of the merged result.
Return the final merged string.
Example 1:
Input: word1 = "abc", word2 = "xyz"
Output: "axbycz"Example 2:
Input: word1 = "ab", word2 = "abbxxc"
Output: "aabbbxxc"Constraints:
1 <= word1.length, word2.length <= 100word1 and word2 consist of lowercase English letters.Before attempting this problem, you should be comfortable with:
We want to interleave characters from both strings, taking one from each in turn. Using two pointers, we can walk through both strings simultaneously. While both strings have characters remaining, we append one from each. Once one string is exhausted, we append whatever remains from the other string.
i and j at 0, and an empty result list.i < len(word1) and j < len(word2):word1[i] to the result, then increment i.word2[j] to the result, then increment j.word1 (from index i to end).word2 (from index j to end).Where and are the lengths of the strings and respectively.
Instead of handling the remaining characters separately after the main loop, we can continue the loop as long as either string has characters left. In each iteration, we check if each pointer is still valid before appending. This approach handles unequal length strings naturally within a single loop.
i and j at 0, and an empty result list.i < n or j < m (where n and m are the lengths of the strings):i < n, append word1[i] and increment i.j < m, append word2[j] and increment j.Where and are the lengths of the strings and respectively.
Since we always process characters at the same index from both strings in each iteration, we can simplify to a single index variable. We iterate up to the length of the longer string, and for each index, we add the character from each string if that index is valid.
n and m be the lengths of word1 and word2.i from 0 to max(n, m) - 1:i < n, append word1[i] to the result.i < m, append word2[i] to the result.Where and are the lengths of the strings and respectively.
When one string is longer than the other, the remaining characters must be appended after the alternating portion is complete. Stopping the loop when the shorter string ends without handling the leftover characters produces an incomplete result.
In many languages, repeatedly concatenating strings with + inside a loop creates a new string object each time, leading to O(n^2) time complexity. Use a StringBuilder, list of characters, or similar efficient structure to build the result, then join at the end.