Site icon vanitaai.com

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.

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.

Example 1:

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

Example 2:

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

Constraints:

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:

Step 2: Calculate Lengths

        m = len(word1)
        n = len(word2)

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

Step 3: Initialize Pointers and Result List

        i, j = 0, 0
        result = []

Step 4: Loop Until All Characters Are Used

        while i < m or j < n:

Step 5: Append Character from word1 If Available

            if i < m:
                result += word1[i]
                i += 1

Step 6: Append Character from word2 If Available

            if j < n:
                result += word2[j]
                j += 1

Step 7: Return Final String

        return "".join(result)

Time and Space Complexity

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

Exit mobile version