Merge Strings Alternately
Difficulty: Easy
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.
Example
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string is formed as: a + p + b + q + c + r = "apbqcr".
Brute-force approach
Use two separate loops: first interleave characters up to the shorter string's length, then append the remainder of the longer string.
Steps
- Find the minimum length of both strings
- Interleave characters up to the minimum length
- Append remaining characters from the longer string
- Return the merged result
Time complexity: O(n + m) · Space complexity: O(n + m)
Trade-offs
- Uses two separate phases (interleave + append)
- Slightly more code than a single-loop approach
- String concatenation in a loop can be O((n+m)²) in some languages
Optimal approach
Key insight: A single index i can traverse both strings simultaneously. Just check bounds before accessing each string.
Use a single loop with one index variable. At each iteration, append from word1 if available, then from word2 if available. Handles unequal lengths naturally.
Steps
- Initialize result list and index i = 0
- Loop while i < len(word1) OR i < len(word2)
- Conditionally append word1[i] then word2[i]
- Increment i
- Return joined result
Time complexity: O(n + m) · Space complexity: O(n + m)