Merge Strings Alternately
The drill: Weave two strings into one, alternating letters from each side; once one string runs dry, tack on whatever remains of the other.
Two strings arrive side by side, and the job is to weave them into one by alternating characters — first character of the first string, then first character of the second, then the second character of the first, and so on.
The two strings are rarely the same length. Once the shorter one is exhausted, the weaving stops alternating and the remaining tail of the longer string is simply appended whole.
Order within each source string is preserved throughout; nothing from either string is ever dropped or reordered relative to its own neighbors.
- each string ranges from a single character up to a few hundred
- the two input strings may differ in length
- only lowercase letters appear in either string
- the leftover tail of the longer string is appended once the shorter runs out
HINT 1 THE NUDGE
Growing the answer with repeated += copies everything built so far on every step — in general that turns a linear-looking pass into quadratic work. What container appends without paying a copy each time?
HINT 2 THE STRUCTURE
Walk one shared index across both strings, taking a character from each side while that side still has one left to give.
HINT 3 ONE STEP FROM THE ANSWER
March i from 0: append word1[i] if it exists, then word2[i] if it exists. Once i passes both lengths the loop stops on its own — the leftover tail of the longer string falls out for free.
Weave word1 and word2 letter by letter: word1's char first, then word2's, at each shared index i.
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
merged = []
n = max(len(word1), len(word2))
for i in range(n):
if i < len(word1):
merged.append(word1[i])
if i < len(word2):
merged.append(word2[i])
return "".join(merged)class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
result = "" # every += below copies the whole string built so far
n = max(len(word1), len(word2))
for i in range(n):
if i < len(word1):
result += word1[i]
if i < len(word2):
result += word2[i]
return resultclass Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder sb = new StringBuilder();
int n = Math.max(word1.length(), word2.length());
for (int i = 0; i < n; i++) {
if (i < word1.length()) {
sb.append(word1.charAt(i));
}
if (i < word2.length()) {
sb.append(word2.charAt(i));
}
}
return sb.toString();
}
}class Solution {
public String mergeAlternately(String word1, String word2) {
String result = ""; // every += below copies the whole string built so far
int n = Math.max(word1.length(), word2.length());
for (int i = 0; i < n; i++) {
if (i < word1.length()) {
result += word1.charAt(i);
}
if (i < word2.length()) {
result += word2.charAt(i);
}
}
return result;
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED