◀ THE GRIND — TWO POINTERS

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.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

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.

EX 01
word1 = "abc" · word2 = "pqr"
"apbqcr"
EQUAL LENGTH, CLEAN ALTERNATION
EX 02
word1 = "ab" · word2 = "pqrs"
"apbqrs"
WORD2 RUNS LONGER
EX 03
word1 = "abcd" · word2 = "pq"
"apbqcd"
WORD1 RUNS LONGER
THE HINTS — TAKE ONLY WHAT YOU NEED
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.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE WEAVEPATTERN · TWO POINTERS, ONE PASSword1 = "abc" · word2 = "pqr"
a
b
c
p
q
r
STEP 1

Weave word1 and word2 letter by letter: word1's char first, then word2's, at each shared index i.

STEP 1 / 8 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/merge-strings-alternately.pyRACE PACE
LANG ▸
PACE ▸
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)
TIME O(N+M)SPACE O(N+M)PYTHON · RACE PACE · 10 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED