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 word1word2word1word2
Example 1
Output: "apbqcr"
Example 2
Output: "apbqrs"
Explanation: after "apbq", word1 is used up, so "rs" is added.
Example 3
Output: "apbqcd"
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"word2 = "pqrs"word1
The rule says they go to the end, in their own order. Look at the picture below.
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
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: iword1jword2
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()
Building the result
Why not join the letters with +String+
A StringBuilderappendtoString()word1.length() + word2.length()
Java Solution
The method mergeAlternately
- First, create a
namedStringBuilder with room forsb characters, and set two indices,word1.length() + word2.length() fori andword1 forj , to 0.word2 - Take turns in a
loop that runs as long aswhile ori has not reached the end of its word.j - Inside the loop, if
still has a letter atword1 , append it toi and movesb forward. Then do the same fori withword2 .j - When both words are used up, the loop ends, and the method returns
.sb.toString()
The mainword1word2
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:
apbqcr
apbqrs
apbqcd
xyz
x
[]
Look at the second line, apbqrsword1apbqcdword1
The lines xyzx[]
The ||&&
The original implementation,
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
andword1 . 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.word2 - 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
andi .j
ij