NeetCode #180LC-1768EasyTwo PointersNC 250
← Back to All Problems

#180 · #1768 · Merge Strings Alternately(交替合并字符串)

📌 Problem Statement & Constraints

You are given two strings word1 and word2. Merge them by adding letters in alternating order, starting with word1. If one string is longer, append its extra letters. Constraints: 1 <= word1.length, word2.length <= 100.

💡 Core Algorithmic Approaches

  1. Walk both strings in lockstep with a shared index, appending one character from each.
  2. Stop the alternation when the shorter string is exhausted.
  3. Then append the remainder of the longer string.
  4. A single loop over range(max(len1, len2)) with bounds checks expresses this compactly.

💻 Benchmark Python3 Implementation

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        res = []
        for i in range(max(len(word1), len(word2))):
            if i < len(word1):
                res.append(word1[i])
            if i < len(word2):
                res.append(word2[i])
        return "".join(res)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m + n): each character is appended once.
💾 Space Complexity
O(m + n) for the result list (unavoidable, since the output has that length).

⚠️ Interview Pitfalls & Follow-ups

  • Looping only to min(len1, len2): the tail of the longer string would be dropped.
  • Using zip: zip truncates to the shorter length, so the tails would be lost unless handled separately.
  • String concatenation in a loop (res += ch): O(n^2) in some languages; building a list and joining is the safe idiom.