InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Merge Strings Alternately

easy Original ↗ 00:00

Problem

Given two strings word1 and word2, merge them by alternating characters: first a character from word1, then one from word2, then word1 again, and so on. If one string is exhausted before the other, append the remaining characters of the longer string. Return the merged string.

Examples

  • word1 = "abc", word2 = "pqr""apbqcr" Equal lengths: characters alternate throughout, 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 contributes nothing.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug