Merge Strings Alternately

Combine two strings by taking one letter from each in turn, then add what is left of the longer one.

Given two strings word1 and word2, merge them into one string by taking letters in turn: a letter of word1, then a letter of word2, and so on. When one string runs out of letters, add the remaining letters of the other one to the end. Return the merged string.

Example 1
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Example 2
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: after "apbq", word1 is used up, so "rs" is added.
Example 3
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Solution

The Idea

Think of shuffling two small piles of cards into one: take the top card of the left pile, then the top card of the right pile, and repeat. Merging strings alternately works the same way with letters. In Example 1, "abc" and "pqr" give a, p, b, q, c, r, which reads "apbqcr".

Example 2 is more interesting, because the words have different lengths. word1 = "ab" has two letters and word2 = "pqrs" has four. The turns go a, p, b, q, and then word1 has nothing left to give. What happens to r and s?

The rule says they go to the end, in their own order. Look at the picture below.

Merging word1 = ab and word2 = pqrs. The letters a, p, b and q drop into places 1 to 4 of the result in turns. Then word1 is used up, so r and s from word2 fill places 5 and 6, giving apbqrs.

The row labelled word1 holds a and b, and the row labelled word2 holds p, q, r and s. Each arrow drops a letter into its place in the row labelled result, numbered 1 to 6. Places 1 to 4 alternate between the two words. Then word1 is used up, and the orange r and s fill places 5 and 6. The result is "apbqrs".

So the leftover letters need no rule of their own. If we keep taking turns and simply skip a word that has no letters left, only the longer word still gives letters, and its rest lands at the end by itself.

Solution Approach

Turning that idea into code means settling three things: how to know which letter of each word comes next, when to stop taking turns, and how to build the result string.

Keeping track of each word

Which letter of each word comes next? Keep one index per word: i for word1 and j for word2. Both start at 0, and each moves forward by one when its letter is taken. Indices that walk through data side by side like this are often called two pointers. Here each one simply walks its own word from start to end.

When to stop taking turns

How long should the turns go on? As long as either word has letters left, so the loop runs while i < word1.length() || j < word2.length(). Inside the loop, each word is checked on its own before its letter is taken. Once the shorter word runs out, its check fails in every later turn, and only the longer word's letters are added.

Building the result

Why not join the letters with +? A Java String cannot be changed, so each + makes a new string and copies every letter collected so far. Over many letters, that copying grows with the square of the total length.

A StringBuilder avoids it. It is a buffer of characters that can grow: append adds a letter at the end, and toString() makes the final string once. Creating it with room for word1.length() + word2.length() characters means it never has to grow.

Java Solution

The method mergeAlternately works in these steps:

  1. First, create a StringBuilder named sb with room for word1.length() + word2.length() characters, and set two indices, i for word1 and j for word2, to 0.
  2. Take turns in a while loop that runs as long as i or j has not reached the end of its word.
  3. Inside the loop, if word1 still has a letter at i, append it to sb and move i forward. Then do the same for word2 with j.
  4. When both words are used up, the loop ends, and the method returns sb.toString().

The main method runs the three examples, then an empty word1, an empty word2, and two empty words, whose result is printed between brackets so that it stays visible.

Java
public class MergeStringsAlternately {

    public static String mergeAlternately(String word1, String word2) {
        StringBuilder sb = new StringBuilder(word1.length() + word2.length());
        int i = 0;
        int j = 0;
        while (i < word1.length() || j < word2.length()) {
            if (i < word1.length()) {
                sb.append(word1.charAt(i++));     // next letter of word1, if any left
            }
            if (j < word2.length()) {
                sb.append(word2.charAt(j++));     // next letter of word2, if any left
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(mergeAlternately("abc", "pqr"));
        System.out.println(mergeAlternately("ab", "pqrs"));
        System.out.println(mergeAlternately("abcd", "pq"));
        System.out.println(mergeAlternately("", "xyz"));
        System.out.println(mergeAlternately("x", ""));
        System.out.println("[" + mergeAlternately("", "") + "]");
    }
}

Running it prints:

Output
apbqcr
apbqrs
apbqcd
xyz
x
[]

Look at the second line, apbqrs. After a, p, b and q, the check on word1 fails in the next two turns, so only r and s are added. The third line, apbqcd, is the same thing the other way round, with c and d left over from word1.

The lines xyz and x show that an empty word needs no special case: only the other word's check ever passes. In the last line, [], both words are empty, so the loop never runs and the method returns an empty string.

The || in the loop condition is what keeps the leftover letters. A version with && instead stops as soon as the shorter word runs out. Tried on its own, it turns "ab" and "pqrs" into "apbq", and "abcd" and "pq" into "apbq" too, so r, s, c and d are lost.

The original implementation, MergeStringsAlternately.java, is on GitHub.

Complexity

The method copies each letter of both words into the builder once, and does nothing else per letter.

  • Time: O(m + n), where m and n are the lengths of word1 and word2. The loop takes one turn per letter of the longer word, and across all turns each of the m + n letters is appended exactly once.
  • Space: O(m + n) for the result. The builder holds all m + n letters of the merged string. Besides it, the method keeps only the two indices i and j.

Two Pointers Basics covers indices that walk side by side, like i and j here, and the other ways two pointers can move.