AAlgoLoopSpaced repetition for LeetCode
EASYTwo PointersLeetCode ↗

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

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

410310
Step-by-step visualization
Start free →

More Two Pointers problems