Merge Strings Alternately — LeetCode 1768 Python Solution

EasyTwo PointersString
Problem
#1768
Reading time
2 min

The problem

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1.

Example

Input
word1 = "abc", word2 = "pqr"
Output
"apbqcr"
Explanation
The merged string will be merged as so:

Python solution

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

Complexity

MeasureComplexity
TimeO(m + n), where m and n are the lengths of the two strings respectively
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1768. Merge Strings Alternately is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 1768. Merge Strings Alternately?
LeetCode 1768. Merge Strings Alternately is rated Easy on LeetCode.
What is the time complexity of LeetCode 1768. Merge Strings Alternately?
The Python solution on this page runs in O(m + n), where m and n are the lengths of the two strings respectively.
What is the space complexity of LeetCode 1768. Merge Strings Alternately?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1768. Merge Strings Alternately cover?
LeetCode 1768. Merge Strings Alternately is tagged Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview