Skip to content
Problem 1768 · LeetCode 1768(opens in a new tab)

Merge Strings Alternately

EasyStrings

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.

Try it on LeetCode(opens in a new tab)
  1. One index, check both wordsO(n + m)
  2. 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

ApproachTimeRelative work for two 100-letter wordsVerdict
One index, check both wordsO(n + m)
Correct and simple; extra checks per letter
Pair up, then add the tailO(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

  1. 1Clarify. Which word goes first? What happens to leftover letters? Can a word be empty?
  2. 2Describe the loop. One index walks both words; at each position take word1's letter, then word2's, if they exist.
  3. 3Tighten it. Only the first min(n, m) positions need both words. After that, one tail is copied as a block.
  4. 4Mention string building. Use a list or StringBuilder and join once, so the work stays linear.
  5. 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?