Merge Strings Alternately

Merge Strings Alternately is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Two Pointers pattern, in the In-place Array Modification subpattern.

Problem statement

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

Topics and companies

Topics: String, Two Pointers, Iteration.

How to practise Merge Strings Alternately on Thita.ai

Starter code is provided in C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(word1.length() + word2.length()) time and O(word1.length() + word2.length()) for the returned string; O(1) auxiliary space excluding the output space.

Open Merge Strings Alternately in the code editor, or read the Merge Strings Alternately editorial for a worked solution with its approach and complexity analysis.

Where Merge Strings Alternately sits in the DSA pattern sheet

Problems related to Merge Strings Alternately

Other problems that use the same In-place Array Modification and Two Pointers techniques:

Preparing this workspace.