Merge Strings Alternately

Easy · Two Pointers · Two Pointers · String

Problem

You are given two non-empty strings word1 and word2. Build a new string by taking letters from them in turn: the first letter of word1, then the first letter of word2, then the second letter of word1, and so on.

When one string runs out of letters, append all the remaining letters of the other one, in order.

Return the merged string.

Examples

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

a, p, b, q, c, r.

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

After "apbq" word1 is used up, so "rs" is appended.

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

After "apbq" word2 is used up, so "cd" is appended.

Constraints

Approaches

Follow-up

How would you merge more than two strings in turn, skipping the ones that run out? What changes if each turn takes k letters instead of one?

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…