Merge Strings Alternately

Easy Top 250
Associated Patterns
Interviewed At (Company Tags)
GoogleAmazonMicrosoft

Problem Description

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.


Examples

Example 1:

Input: word1 = “abc”, word2 = “pqr” Output: “apbqcr” Explanation: The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r

Example 2:

Input: word1 = “ab”, word2 = “pqrs” Output: “apbqrs” Explanation: Notice that as word2 is longer, “rs” is appended to the end. word1: a b word2: p q r s merged: a p b q r s


Constraints

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

Moving Parallel Indices

We can solve this problem efficiently by using two pointers, i and j, initialized to 0 to track our progress through word1 and word2 respectively. In a single loop that continues as long as either pointer has characters remaining, we append word1[i] if i < word1.length and increment i, followed by appending word2[j] if j < word2.length and increment j. This handles both the alternating merging and the appending of any remaining suffix in a single, clean loop.


Solution 1: Double Pointer Traversal

Use two indices to track characters and alternate additions to the result.

class Solution {
    public String mergeAlternately(String word1, String word2) {
        StringBuilder sb = new StringBuilder();
        int i = 0, j = 0;
        int n1 = word1.length();
        int n2 = word2.length();
        while (i < n1 || j < n2) {
            if (i < n1) {
                sb.append(word1.charAt(i++));
            }
            if (j < n2) {
                sb.append(word2.charAt(j++));
            }
        }
        return sb.toString();
    }
}
class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        res = []
        i, j = 0, 0
        n1, n2 = len(word1), len(word2)
        while i < n1 or j < n2:
            if i < n1:
                res.append(word1[i])
                i += 1
            if j < n2:
                res.append(word2[j])
                j += 1
        return "".join(res)
#include <string>

class Solution {
public:
    std::string mergeAlternately(std::string word1, std::string word2) {
        std::string res = "";
        int i = 0, j = 0;
        int n1 = word1.length();
        int n2 = word2.length();
        while (i < n1 || j < n2) {
            if (i < n1) {
                res += word1[i++];
            }
            if (j < n2) {
                res += word2[j++];
            }
        }
        return res;
    }
};

Complexity Analysis

  • Time Complexity: O(n + m) where n and m are the lengths of word1 and word2 respectively, since we visit every character exactly once.
  • Space Complexity: O(1) auxiliary space (excluding the output string builder).

Where It Breaks

If the inputs are extremely large, using naive string concatenation (+=) in C++ or Python within a loop causes reallocation overhead. Using pre-allocated structures or string builders resolves this issue.


Common Mistakes

  • Incorrect loop termination: Using an && operator instead of || in the loop condition, which causes the loop to terminate prematurely when the shorter string ends.
  • Ignoring string builder usage: Using immutable string concatenation inside loops in Java, which degrades time complexity to quadratic bounds.

Frequently Asked Questions

Can we use built-in functions? In Python, you can use zip() or zip_longest(), but you still have to merge the remaining character slices manually. A simple manual loop is usually preferred in technical interviews to show index-level tracking.

What happens if one string is empty? The loops will skip appending characters for that empty string and copy all characters from the other string directly.


← All Problems