Merge Strings Alternately

Easy Arrays & Hashing Two Pointer

Merge Strings Alternately is a easy arrays & hashing problem solved with the two pointer pattern. The best approach, optimal (one shared index), runs in O(n + m) time and O(n + m) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from two pointers, then copy the tail up.

Problem

You are given two strings, word1 and word2. Build a new string by taking letters from them in turns: the first letter of word1, then the first letter of word2, then the second letter of word1, then the second letter of word2, and so on.

When one of the words runs out of letters, stop alternating and append all the remaining letters of the other word, in their original order, to the end.

Return the merged string.

Examples

Example 1

Input
word1 = "abc", word2 = "xyz"
Output
"axbycz"
Why
Both words have three letters, so the letters simply take turns: a from word1, x from word2, b, y, c, z.

Example 2

Input
word1 = "hi", word2 = "there"
Output
"htihere"
Why
The turns give h, t, i, h. Then word1 has run out, so the rest of word2, "ere", is added at the end.

Example 3

Input
word1 = "keep", word2 = "on"
Output
"koenep"
Why
The turns give k, o, e, n. Now word2 is used up, and the leftover "ep" of word1 goes at the end.

Constraints

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

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Two pointers, then copy the tailO(n + m)O(n + m)
Optimal (one shared index)O(n + m)O(n + m)

1Two pointers, then copy the tail

TimeO(n + m)Every letter of both words is copied into the builder exactly once.
SpaceO(n + m)The builder holds the answer, n + m letters; apart from it only two indexes are used.

Keep a pointer i into word1 and a pointer j into word2. While both words still have letters, append word1[i] and then word2[j], and move both pointers forward. When the loop stops, at least one word is used up. The other may still have letters left, and those belong at the end in their original order, so append the rest of word1 from i and the rest of word2 from j. One of those two tails is always empty.

  1. Start with an empty builder and i = j = 0.
  2. While i < word1.length and j < word2.length: append word1[i++], then append word2[j++].
  3. Append word1 from i to the end, then word2 from j to the end.
  4. Return the built string.
class Solution {
    public String mergeAlternately(String word1, String word2) {
        StringBuilder sb = new StringBuilder();
        int i = 0, j = 0;
        while (i < word1.length() && j < word2.length()) {
            sb.append(word1.charAt(i++));
            sb.append(word2.charAt(j++));
        }
        sb.append(word1.substring(i));
        sb.append(word2.substring(j));
        return sb.toString();
    }
}

2Optimal (one shared index)

TimeO(n + m)The loop runs max(n, m) times and appends each of the n + m letters once.
SpaceO(n + m)Only the answer itself, of length n + m, plus one index.

Both words are read at the same speed, so a single index is enough. For k from 0 up to the length of the longer word, append word1[k] if word1 is long enough, then word2[k] if word2 is long enough. While both words have a letter at k this alternates; once the shorter word is past its end, its check simply fails and only the longer word's letters are appended, which is exactly the tail. Reserving n + m characters up front means the builder never has to grow.

  1. Let n = word1.length, m = word2.length, and make a builder with room for n + m letters.
  2. For k = 0 to max(n, m) - 1: if k < n append word1[k]; if k < m append word2[k].
  3. Return the built string.
class Solution {
    public String mergeAlternately(String word1, String word2) {
        int n = word1.length(), m = word2.length();
        StringBuilder sb = new StringBuilder(n + m);
        for (int k = 0; k < Math.max(n, m); k++) {
            if (k < n) sb.append(word1.charAt(k));
            if (k < m) sb.append(word2.charAt(k));
        }
        return sb.toString();
    }
}

Edge cases to test

  • Both words have one letter: the answer is just the two letters, word1's first
  • Words of equal length: no leftover at all
  • word2 much longer than word1: after one round of turns almost the whole of word2 is copied as the tail
  • word1 longer than word2: the tail comes from word1, not word2
  • The merged string always has exactly word1.length + word2.length letters

Hints

Hint 1

Keep one position in each word. Take a letter from word1, then one from word2, and move both positions forward.

Hint 2

As soon as one word runs out, nothing is left to alternate with. Whatever remains of the other word is copied to the end in order.

Hint 3

Equivalently, look at index k = 0, 1, 2, ... up to the longer length and append word1[k] and then word2[k], skipping a word that is too short.

FAQ

What is the best time complexity for Merge Strings Alternately?

Optimal (one shared index) runs in O(n + m) time and O(n + m) extra space. The loop runs max(n, m) times and appends each of the n + m letters once.

Which pattern does Merge Strings Alternately use?

It is a arrays & hashing problem that uses the two pointer pattern. Other problems with the same pattern: Two Sum II - Input Array Is Sorted, Valid Triangle Number, Container With Most Water.

Is there a brute force solution for Merge Strings Alternately?

Yes. Two pointers, then copy the tail takes O(n + m) time and O(n + m) space. Keep a pointer i into word1 and a pointer j into word2.

Which edge cases should I test for Merge Strings Alternately?

Both words have one letter: the answer is just the two letters, word1's first; Words of equal length: no leftover at all; word2 much longer than word1: after one round of turns almost the whole of word2 is copied as the tail; word1 longer than word2: the tail comes from word1, not word2; The merged string always has exactly word1.length + word2.length letters.