Strings / Merge

Merge Strings Alternately

Easy
Solve this question in LeetCode

Given two strings word1 and word2, merge them by alternating characters starting with word1. If one string is longer, append the remaining characters at the end.

Example

Example 1
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"

Example 2
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"

Example 3
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"

Example 4
Input: word1 = "", word2 = "xyz"
Output: "xyz"

Example 5
Input: word1 = "x", word2 = ""
Output: "x"

Explanation

  1. We start with two input strings called word1 and word2.
  2. Create an empty StringBuilder named result. Think of it as a flexible box where we drop letters.
  3. Set two counters: i = 0 for word1 and j = 0 for word2. These point to the next letter to take.
  4. Repeat these steps while there are letters left in either word (i < word1.length() or j < word2.length()):
    • If i < word1.length(), take word1.charAt(i), append it to result, then increase i by 1.
    • If j < word2.length(), take word2.charAt(j), append it to result, then increase j by 1.
  5. If one word runs out first, simply skip it and keep taking letters from the other word until it is finished.
  6. When the loop ends, convert result to a regular string with result.toString(). That is the merged answer.

Quick example: word1 = "ab", word2 = "pqrs" → result builds as "a""ap""apb""apbq""apbqr""apbqrs".

Idea Map

Start

Initialize i = 0, j = 0, n1 = len(word1), n2 = len(word2), sb = new StringBuilder()

Loop while i < n1 || j < n2

True

1. If i < n1, append word1.charAt(i++)
2. If j < n2, append word2.charAt(j++)

Return sb.toString()

End

Code (Java)


class Solution {
Defines the Solution class as expected by the LeetCode environment.
public String mergeAlternately(String word1, String word2) {
Method signature: takes two input strings and returns their alternating merge.
StringBuilder result = new StringBuilder();
Use StringBuilder for efficient, mutable string construction.
int length1 = word1.length();
Cache lengths to avoid repeated method calls in the loop.
int length2 = word2.length();
Length of the second string.
int i = 0, j = 0;
Two indices to track positions in word1 and word2.
while (i < length1 || j < length2) {
Continue while either string has characters remaining.
if (i < length1)
Append from word1 if there is a character available.
result.append(word1.charAt(i++));
Append one character from word1 and increment i.
if (j < length2)
Append from word2 if there is a character available.
result.append(word2.charAt(j++));
Append one character from word2 and increment j.
}
End of the loop.
return result.toString();
Convert the StringBuilder to an immutable string and return.
}
End of method.
}
End of class.

What is String Concatenation in Java?

String concatenation is the process of joining strings together. In Java, you can concatenate using the + operator or String.concat. Because String is immutable, repeated concatenation in loops can be inefficient — prefer StringBuilder (or StringBuffer in multi-threaded contexts) for better performance.

// Examples
String a = "Hello" + ", " + "World"; // simple
String b = "Hi".concat(" ").concat("there");
StringBuilder sb = new StringBuilder();
sb.append("A").append("B");
String c = sb.toString();
Learn more about Java String Concatenation →
lightbulb

Disclaimer: This problem is for educational purposes. We encourage you to try solving the 'Merge Strings Alternately' question on LeetCode.