645/670

645. Merge Strings Alternately

Easy

You are given two strings, word1 and word2. Weave them into one string by taking letters in turns: the first letter of word1, then the first letter of word2, then the second letter of word1, and so on, always starting with word1.

If one string runs out of letters before the other, append everything left over from the longer string to the end. Return the merged string.

Example 1:

Input: word1 = "abc", word2 = "pqr"

Output: "apbqcr"

Explanation: Both words have 3 letters, so the turns alternate perfectly: a, p, b, q, c, r.

Example 2:

Input: word1 = "ab", word2 = "pqrs"

Output: "apbqrs"

Explanation: word1 is exhausted after "apbq", so word2's leftover "rs" is appended.

Example 3:

Input: word1 = "abcd", word2 = "pq"

Output: "apbqcd"

Explanation: word2 is exhausted after "apbq", so word1's leftover "cd" is appended.

Constraints:

  • 1 ≤ word1.length, word2.length ≤ 100
  • word1 and word2 consist of lowercase English letters

Hints:

Walk both strings with one index i: at each i, append word1[i] if it exists, then word2[i] if it exists. Loop i up to the longer length.

In languages with immutable strings, collect the characters in a list/builder and join once at the end instead of concatenating in a loop.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: word1 = "abc", word2 = "pqr"

Expected output: "apbqcr"