Merge Strings Alternately Visualizer & Step-by-Step Algorithm Solution

Merge characters from word1 and word2 in alternating order, appending any remaining suffix characters.

Category: arrays | Difficulty: Easy

Tags: Two Pointers, String, Simulation

Merge Strings Alternately

Word 1: "abc" (length 3)
a
0
b
1
c
2
Word 2: "pqr" (length 3)
p
0
q
1
r
2
Merged Result: "" (length 0)
100%
state
result""
word1.length3
word2.length3
max length3
Initialize
1/12
Explanation

Initialize empty result string. Word 1 length = 3, Word 2 length = 3.

Source Code
1function mergeAlternately(word1: string, word2: string): string {
2 let result = "";
3 for (let i = 0; i < Math.max(word1.length, word2.length); i++) {
4 if (i < word1.length) result += word1[i];
5 if (i < word2.length) result += word2[i];
6 }
7 return result;
8}