You are given two lowercase strings, word1 and word2. Build a new string by taking letters from them in turns: the first letter of word1, then the first of word2, then the second of word1, and so on.
When one word runs out of letters, put whatever is left of the other word at the end, in its original order. Return the combined string.
Example 1
Input: word1 = "dog", word2 = "cat" Output: "dcoagt" Why: d c, o a, g t: the words take turns, word1 first
2 more examples and the constraints
Example 2
Input: word1 = "hi", word2 = "wxyz" Output: "hwixyz" Why: after h w i x, word1 is used up, so "yz" goes last
Example 3
Input: word1 = "true", word2 = "no" Output: "tnroue" Why: after t n r o, the rest of word1, "ue", goes last
Constraints
- 1 ≤ length of word1, length of word2 ≤ 100
- Both words contain only the lowercase letters a to z
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- One index, check both wordsO(n + m)
- Pair up, then add the tailO(n + m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two 100-letter words | Verdict |
|---|---|---|---|
| One index, check both words | O(n + m) | Correct and simple; extra checks per letter | |
| Pair up, then add the tail | O(n + m) | Best; no checks inside the loop |
n and m = the lengths of word1 and word2.
Edge cases to test
- Equal lengths. Both tails are empty, so the answer is just the pairs.
- One word has a single letter. "q" and "rstu" give "qrstu": one pair, then the long tail.
- word1 is the longer one. Its tail goes on the end, not word2's.
- Repeated letters. "aaa" and "aa" give "aaaaa"; nothing is deduplicated.
Common mistakes
- Stopping when the shorter word ends and dropping the longer word's leftover letters.
- Starting with word2's letter instead of word1's.
- Reading
word1[i]past its end instead of checking the length first.
How to talk through it
- 1Clarify. Which word goes first? What happens to leftover letters? Can a word be empty?
- 2Describe the loop. One index walks both words; at each position take word1's letter, then word2's, if they exist.
- 3Tighten it. Only the first min(n, m) positions need both words. After that, one tail is copied as a block.
- 4Mention string building. Use a list or StringBuilder and join once, so the work stays linear.
- 5Test out loud. Run equal lengths, word1 longer and word2 longer.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?