Solution 1 - Two Pointers
Alternate characters while both remain, then append leftover.
TimeComplexity:O(n+m)
SpaceComplexity:O(n+m)
function mergeAlternately(word1, word2){
let out=[];
for(let i=0;i<Math.max(word1.length, word2.length);i++){
if(i<word1.length) out.push(word1[i]);
if(i<word2.length) out.push(word2[i]);
}
return out.join('');
}function mergeAlternately(word1:string, word2:string):string{
const out:string[]=[];
for(let i=0;i<Math.max(word1.length, word2.length);i++){
if(i<word1.length) out.push(word1[i]);
if(i<word2.length) out.push(word2[i]);
}
return out.join('');
}package main
func mergeAlternately(word1 string, word2 string) string {
out := make([]byte, 0, len(word1)+len(word2))
for i := 0; i < len(word1) || i < len(word2); i++ {
if i < len(word1) { out = append(out, word1[i]) }
if i < len(word2) { out = append(out, word2[i]) }
}
return string(out)
}
func main() {}fn merge_alternately(word1: &str, word2: &str) -> String {
let a: Vec<char> = word1.chars().collect();
let b: Vec<char> = word2.chars().collect();
let mut out = String::new();
for i in 0..a.len().max(b.len()) {
if i < a.len() { out.push(a[i]); }
if i < b.len() { out.push(b[i]); }
}
out
}
fn main() {}