Skip to main content

Merge Strings Alternately

Easy
Data Structures and Algorithms
Editorial
Topics:
String
Two Pointers
Iteration

Implement mergeAlternately to combine the characters of word1 and word2 into one string. Begin with the first character of word1, then the first character of word2, and continue by taking the next character from each string in turn whenever that string still has an unused character.

If one string ends before the other, append all remaining characters from the longer string in their original order. Return the resulting merged string.

Example 1:

Input: word1 = "cat", word2 = "DOG"
Output: "cDaOtG"
Explanation: Characters are selected in alternating order until both strings have been consumed.

Example 2:

Input: word1 = "sun", word2 = "x"
Output: "sxun"
Explanation: The first characters alternate, then the remaining characters of word1 are appended.

Example 3:

Input: word1 = "q", word2 = "lamp"
Output: "qlamp"
Explanation: After taking q and l, the unused suffix amp is copied to the result.

Constraints:

  • 1 <= word1.length <= 100
  • 1 <= word2.length <= 100
  • ``word1 contains only lowercase English letters
  • ``word2 contains only lowercase English letters

Need help or want more practice?

Practise in an interviewGet AI Coach help