{x}
blog image

Merge Strings Alternately

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.

 

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

Example 3:

Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1:  a   b   c   d
word2:    p   q 
merged: a p b q c   d

 

Constraints:

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

Solution Explanation for Merge Strings Alternately

This problem involves merging two strings, word1 and word2, in an alternating fashion. The process starts by taking a character from word1, then a character from word2, and so on. If one string is longer, its remaining characters are appended to the end of the merged string.

Approach

The most efficient approach uses two pointers (implicit in many solutions) to iterate through both strings simultaneously. We maintain an index for each string and increment them alternately. The process continues until both strings are exhausted.

Code Implementation and Explanation (Python)

The Python solution leverages the zip_longest function from the itertools module. This function pairs elements from two iterables, filling in missing values with a specified default (here, an empty string ''). This elegantly handles strings of unequal length.

from itertools import zip_longest
 
class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue=''))
 

Explanation:

  1. from itertools import zip_longest: Imports the zip_longest function.
  2. zip_longest(word1, word2, fillvalue=''): This creates an iterator that yields pairs of characters from word1 and word2. If one string is shorter, fillvalue='' ensures that the longer string's remaining characters are paired with an empty string.
  3. a + b for a, b in ...: This is a generator expression that concatenates the characters from each pair.
  4. ''.join(...): Joins the concatenated characters into a single string, which is the merged string.

Code Implementation and Explanation (Java)

The Java solution utilizes a StringBuilder for efficient string manipulation and avoids the overhead of repeatedly creating new strings.

class Solution {
    public String mergeAlternately(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < m || i < n; ++i) {
            if (i < m) {
                ans.append(word1.charAt(i));
            }
            if (i < n) {
                ans.append(word2.charAt(i));
            }
        }
        return ans.toString();
    }
}

Explanation:

  1. int m = word1.length(), n = word2.length();: Gets the lengths of both strings.
  2. StringBuilder ans = new StringBuilder();: Creates a StringBuilder to store the merged string efficiently.
  3. for (int i = 0; i < m || i < n; ++i): Iterates until the end of the longest string is reached.
  4. if (i < m) { ans.append(word1.charAt(i)); } and if (i < n) { ans.append(word2.charAt(i)); }: Appends characters alternately from word1 and word2.
  5. return ans.toString();: Converts the StringBuilder to a String and returns it.

Time and Space Complexity Analysis

Time Complexity: O(m + n), where 'm' and 'n' are the lengths of word1 and word2 respectively. We iterate through each string at most once.

Space Complexity: O(m + n) in the worst case (if both strings have roughly equal lengths). This is due to the space used to store the merged string. The space complexity can be considered O(1) if we disregard the output string's space. The auxiliary space used by variables is constant regardless of input size.