InterviewPrepKit

Home / Coding / Two Pointers

Merge Strings Alternately

easy Original ↗
Solving tips
  • Unify both phases into one rule: for i from 0 to max(len1,len2)-1, append word1[i] if it exists then word2[i] if it exists; the leftover tail falls out for free.
  • Collect into a list and ''.join once instead of repeated string += (which is accidentally O(n^2) on large inputs).
  • itertools.zip_longest(word1, word2, fillvalue='') gives a clean declarative one-liner for the same algorithm.
  • O(m+n) time and space; keep the fixed word1-then-word2 order and don't stop the loop at min(len1,len2).

Problem

Given two strings word1 and word2, weave them together by alternating characters: first a character from word1, then one from word2, then word1 again, and so on. If one string runs out before the other, append everything left over from the longer string to the end. Return the merged string.

Examples

  • word1 = "abc", word2 = "pqr""apbqcr" Equal lengths: characters alternate perfectly, a-p, b-q, c-r.
  • word1 = "ab", word2 = "pqrs""apbqrs" word1 runs out after two rounds; the remaining "rs" of word2 is appended.
  • word1 = "abcd", word2 = "pq""apbqcd" word2 runs out first; "cd" from word1 finishes the string.

Constraints

  • 1 <= word1.length, word2.length <= 100
  • Both strings consist of lowercase English letters.

Think about it first

Hint 1 The answer has exactly `len(word1) + len(word2)` characters — every input character appears exactly once, only the order is in question.
Hint 2 Keep one index per string. At each round, append from whichever strings still have characters left — in `word1`-then-`word2` order.
Hint 3 Loop `i` from `0` to `max(len(word1), len(word2)) - 1`; at each `i` append `word1[i]` if it exists, then `word2[i]` if it exists. The "leftover tail" case falls out automatically because the exhausted string simply contributes nothing.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.