Merge Strings Alternately
Easy
Topics
Merge s and t by taking characters alternately, starting with s.
If one string is longer, append its remaining characters to the end of the merged string.
Example 1
s, and the shading in the merged row records which string each one came from. Both strings are the same length here, so the shades alternate the whole way and there is no leftover run.Input: s = "abc", t = "pqr" Output: "apbqcr" Explanation: Equal lengths, so the alternation runs the whole way.
Example 2
t are appended in one unbroken run rather than continuing to alternate.Input: s = "ab", t = "pqrs" Output: "apbqrs" Explanation: After two rounds s is exhausted, so the rest of t follows unchanged.
Example 3
Input: s = "abcd", t = "pq" Output: "apbqcd" Explanation: The same the other way round — and the leftover comes from s, which starts the alternation.
Constraints
- 1 <= s.length, t.length <= 100
- s and t consist of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls
Intuition
Two cursors, one per string, and a flag for whose turn it is — that is the literal reading, and the flag is unnecessary. Walking a single index i over both strings at once takes s[i] then t[i] at every step, which is the alternation.
The leftover then handles itself: run i to the length of the longer string and append each character only when that string is long enough to have one. No separate phase and no flag.
Writing it as "alternate until one runs out, then append the rest" is equally correct and splits into two loops. The single-index version is shorter and has one fewer place to make an off-by-one.
Approach
- Let
irun from 0 to the length of the longer string. - If
iis a valid index ofs, appends[i]. - If
iis a valid index oft, appendt[i]. - Join the collected characters.
Walkthrough
s = "ab"
t = "pqrs"
i from s from t output
0 a p "ap"
1 b q "apbq"
2 -- r "apbqr"
3 -- s "apbqrs"
answer "apbqrs"
From i = 2 onwards only t has characters, and the leftover
falls out of the bounds test rather than needing its own loop.Complexity
- Time — O(n + m): one pass over the longer string, appending at most two characters per step.
- Space — O(n + m): the output.
Common Pitfalls
- Appending the leftover from the wrong string, or appending both leftovers. Only one string can have characters remaining.
- Stopping at the shorter length and forgetting the remainder entirely.
- Starting with
t. The alternation begins withs, which is what distinguishes examples 2 and 3. - Building the result by repeated string concatenation in a language with immutable strings, which turns a linear merge quadratic.
Full Solution — all languages
class Solution:
def mergeAlternately(self, s, t):
out = []
for i in range(max(len(s), len(t))):
if i < len(s):
out.append(s[i])
if i < len(t):
out.append(t[i])
return "".join(out)import java.util.*;
class Solution {
public String mergeAlternately(String s, String t) {
StringBuilder out = new StringBuilder();
for (int i = 0; i < Math.max(s.length(), t.length()); i++) {
if (i < s.length()) out.append(s.charAt(i));
if (i < t.length()) out.append(t.charAt(i));
}
return out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string mergeAlternately(string s, string t) {
string out;
for (size_t i = 0; i < max(s.size(), t.size()); i++) {
if (i < s.size()) out += s[i];
if (i < t.size()) out += t[i];
}
return out;
}
};/**
* @param {string} s
* @param {string} t
* @return {string}
*/ var mergeAlternately = function(s, t) {
let out = "";
for (let i = 0; i < Math.max(s.length, t.length); i++) {
if (i < s.length) out += s[i];
if (i < t.length) out += t[i];
}
return out;
};