Array / String· 15 min

Merge Strings Alternately

LeetCode #1768 · Easy · Interactive step-by-step visualization

Setup

Example inputword1 = "abc", word2 = "pqrstu"
Step 1 / 20

Current step

1 / 20

Place one cursor at the start of each string. The output is initially empty.

Step log

result

No values to display.

Active
Comparing
Committed
Rejected or blocked
merge-strings-alternately.java
1public String mergeAlternately(String word1, String word2) {
2 StringBuilder result = new StringBuilder();
3 for (int i = 0; i < Math.max(word1.length(), word2.length()); i++) {
4 if (i < word1.length()) result.append(word1.charAt(i));
5 if (i < word2.length()) result.append(word2.charAt(i));
6 }
7 return result.toString();
8}
● Java
Time
O(n + m)
Space
O(n + m)
Pattern
two pointers
Frames
20