Build a new string by taking characters alternately from two input strings.
Problem
Given two strings, construct a new string by alternating characters from the first and second strings, starting with the first string.
- Take the first character from the first string, then the first character from the second string.
- Continue alternating characters from each string.
- If one string runs out of characters first, append the remaining characters from the other string to the end.
Return the merged string.
This is a straightforward string-building problem that tests careful indexing and simulation.
Input Format
- Two strings
word1andword2. - Each string contains lowercase English letters.
Output Format
- Return a single string formed by alternating characters from
word1andword2.
Constraints
- Strings contain only lowercase English letters.
- The result length is .
Example 1
Input
word1 = "abc", word2 = "pqr"
Output
"apbqcr"
Explanation
Take a from word1, p from word2, b from word1, q from word2, c from word1, r from word2.
Example 2
Input
word1 = "ab", word2 = "pqrs"
Output
"apbqrs"
Explanation
Alternate until word1 ends, then append the remaining characters from word2.
Show 1 more example
Example 3
Input
word1 = "abcd", word2 = "pq"
Output
"apbqcd"
Explanation
Alternate until word2 ends, then append the remaining characters from word1.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.