#1768
Easy Algorithms Merge strings alternately
Two Pointers String
82.1% acceptance
Feb 25, 2026
4880
143
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn merge_alternately(word1: String, word2: String) -> String {
let (b1, b2) = (word1.as_bytes(), word2.as_bytes());
let (n1, n2) = (b1.len(), b2.len());
let mut result = Vec::with_capacity(n1 + n2);
let mut i = 0;
while i < n1 || i < n2 {
if i < n1 { result.push(b1[i]); }
if i < n2 { result.push(b2[i]); }
i += 1;
}
String::from_utf8(result).unwrap()
}
}