Merge Strings Alternately

Easy
254.

Merge Strings Alternately

Merge Strings Alternately is an easy coding problem on strings and two pointers, asked in Amazon, Google and Zoho interviews.

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 remaining letters to the end of the merged string.

Example 1

Input
word1 = "abc", word2 = "pqr"
Output
apbqcr

Example 2

Input
word1 = "ab", word2 = "pqrs"
Output
apbqrs
Explanation
After "ab" runs out, the rest of word2 is appended.

Example 3

Input
word1 = "abcd", word2 = "pq"
Output
apbqcd

Constraints

  • 1 <= word1.length, word2.length <= 30
  • Both consist of lowercase English letters.
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {string} word1
 * @param {string} word2
 * @return {string}
 */
var mergeAlternately = function(word1, word2) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Merge Strings Alternately — Solution in Python, Java & C++

Merge Strings Alternately solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.

Merge Strings Alternately is an easy coding problem on strings and two pointers, asked in Amazon, Google and Zoho interviews.

  • Difficulty: Easy
  • Topics: Strings, Two Pointers
  • Asked at: Amazon, Google, Zoho
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

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 remaining letters to the end of the merged string.

Example 1

Input: word1 = "abc", word2 = "pqr"
Output: apbqcr

Example 2

Input: word1 = "ab", word2 = "pqrs"
Output: apbqrs
Explanation: After "ab" runs out, the rest of word2 is appended.

Example 3

Input: word1 = "abcd", word2 = "pq"
Output: apbqcd

Constraints

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

Hints for Merge Strings Alternately

  1. Hint 1

    Loop up to the length of the longer string.

  2. Hint 2

    At each step append word1[i] if it exists, then word2[i] if it exists.

  3. Hint 3

    That single loop handles the leftover tail without a separate append step.

How to solve Merge Strings Alternately

Loop to the longer length, appending word1[i] then word2[i] whenever each exists; the tail of the longer word falls out naturally.

Approach

  1. For i in 0 .. max(len1, len2) - 1: append word1[i] if i < len1, then word2[i] if i < len2.
  2. Join.

Why it works

Alternation is index-by-index interleaving, and the bounds checks make the leftover characters of the longer string append in order once the shorter one runs out.

Complexity

  • Time — O(n + m)
  • Space — O(n + m)

Pitfalls

  • Looping to the shorter length and appending the remainder separately also works — just remember both possible tails.

Reference solution

Python

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

Java

public static String mergeAlternately(String word1, String word2) {
    StringBuilder out = new StringBuilder();
    int n = Math.max(word1.length(), word2.length());
    for (int i = 0; i < n; i++) {
        if (i < word1.length()) out.append(word1.charAt(i));
        if (i < word2.length()) out.append(word2.charAt(i));
    }
    return out.toString();
}

C++

string mergeAlternately(string word1, string word2) {
    string out = "";
    size_t n = max(word1.size(), word2.size());
    for (size_t i = 0; i < n; i++) {
        if (i < word1.size()) out += word1[i];
        if (i < word2.size()) out += word2[i];
    }
    return out;
}

JavaScript

var mergeAlternately = function(word1, word2) {
    let out = "";
    const n = Math.max(word1.length, word2.length);
    for (let i = 0; i < n; i++) {
        if (i < word1.length) out += word1[i];
        if (i < word2.length) out += word2[i];
    }
    return out;
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 515 strings problems · the whole catalogue

Learn the technique: Strings · Two Pointers Technique