LeetCode75: Merge Strings Alternately

The Merge Strings Alternately problem is a simple yet elegant string manipulation task often featured in beginner-level coding challenges and interview warmups. Given two input strings, word1 and word2, your goal is to merge them character by character in alternating order starting with the first character of word1, followed by the first character of word2, and continuing this pattern.

Merge String Alternatively

If the strings are of unequal lengths, the extra characters from the longer string should simply be appended to the end of the merged result.

This problem helps build a strong foundation in string traversal, loop control, and handling edge cases like mismatched string lengths. In the following explanation, we’ll walk through a clean and efficient Python solution to the Merge Strings Alternately problem, ensuring a solid understanding of the logic and implementation.

You are given two strings, word1 and word2. Your task is to merge the strings alternately, by appending characters from each string one by one, starting with the first character of word1 then word2 and so on.

  • If one string is longer than the other, append the remaining characters of the longer string to the merged result.

Example 1:

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

Example 2:

Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"

Constraints:

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

Python Solution

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        m = len(word1)
        n = len(word2)
        i, j = 0, 0
        result = []
        while i < m or j < n:
            if i < m:
                result += word1[i]
                i += 1
            if j < n:
                result += word2[j]
                j += 1
        return "".join(result)

Step-by-Step Explanation

Step 1: Define the Function

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
  • A method mergeAlternately is created under the class Solution.
  • It accepts two input strings: word1 and word2.

Step 2: Calculate Lengths

        m = len(word1)
        n = len(word2)
  • m stores the length of word1
  • n stores the length of word2

These are used to control the iteration process over each string.

Step 3: Initialize Pointers and Result List

        i, j = 0, 0
        result = []
  • i and j are pointers for tracking the current index in word1 and word2 respectively.
  • result is a list used to build the merged string efficiently.

Step 4: Loop Until All Characters Are Used

        while i < m or j < n:
  • The loop runs as long as there are remaining characters in either word1 or word2.

Step 5: Append Character from word1 If Available

            if i < m:
                result += word1[i]
                i += 1
  • If the current index i is within bounds, the i-th character from word1 is added to the result.
  • Increment i to move to the next character.

Step 6: Append Character from word2 If Available

            if j < n:
                result += word2[j]
                j += 1
  • Similarly, if j is within bounds, the j-th character from word2 is added.
  • Increment j.

Step 7: Return Final String

        return "".join(result)
  • The list result is joined into a single string using "".join() and returned as the final merged string.

Time and Space Complexity

  • Time Complexity: O(m + n)
    Since we traverse both strings once
  • Space Complexity: O(m + n)
    For storing the characters in the result list

Summary

The mergeAlternately function is a simple and efficient way to merge two strings character by character. It handles different string lengths and uses pointer-based iteration to alternate between characters from word1 and word2.

LeetCode75: Python Solution-Product of Array Except Self

1 thought on “LeetCode75: Merge Strings Alternately”

Leave a Comment