Merge Strings Alternately
Merge two strings by adding letters in alternating order, starting with word1. If one string is longer, append the remaining letters to the end.
Example 1
Input: word1="abc", word2="pqr" → Output: "apbqcr"
Example 2
Input: word1="ab", word2="pqrs" → Output: "apbqrs"
Solution Approach
Use two pointers advancing through both strings simultaneously. Append from word1 then word2 in turns.
- Use pointers i and j starting at 0.
- While either i < word1.length or j < word2.length:
- Append word1[i] if i is valid; append word2[j] if j is valid.
- Advance both.
Java
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder sb = new StringBuilder();
int i = 0, j = 0;
while (i < word1.length() || j < word2.length()) {
if (i < word1.length()) sb.append(word1.charAt(i++));
if (j < word2.length()) sb.append(word2.charAt(j++));
}
return sb.toString();
}
}
- Time Complexity: O(N+M)
- Space Complexity: O(N+M)