Merge Strings Alternately
The key idea
Walk both strings with one shared index. At each position, take word1's char then word2's char when they still exist. When one string runs out, the remaining characters of the longer string are simply appended in order.
Problem
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
Constraints
- 1 <= word1.length, word2.length <= 100
- word1 and word2 consist of lowercase English letters.
Examples
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Complexity
Time: O(n + m) Space: O(n + m)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Two Pointers problems
- 3SumMEDIUM
- 4SumMEDIUM
- Concatenation of ArrayEASY
- Container With Most WaterMEDIUM
- Is SubsequenceEASY
- Merge Sorted ArrayEASY
- Move ZeroesEASY
- Next PermutationMEDIUM
- Remove Duplicates from Sorted ArrayEASY
- Remove Duplicates from Sorted Array IIMEDIUM
- Remove ElementEASY
- Reverse StringEASY