Program to merge strings alternately using Python

Suppose we have two strings s and t. We have to merge them by adding letters in alternating fashion, starting from s. If s and t are not of same length, add the extra letters onto the end of the merged string.

So, if the input is like s = "major" and t = "general", then the output will be "mgaejnoerral". Since t is larger than s, we have added extra part "ral" at the end.

Algorithm

To solve this, we will follow these steps −

  • Initialize i := j := 0

  • result := blank string

  • while i < size of s and j < size of t, do

    • result := result concatenate s[i] concatenate t[j]

    • i := i + 1

    • j := j + 1

  • while i < size of s, do

    • result := result concatenate s[i]

    • i := i + 1

  • while j < size of t, do

    • result := result concatenate t[j]

    • j := j + 1

  • return result

Using Two Pointers

Let us see the following implementation to get better understanding −

def solve(s, t):
    i = j = 0
    result = ""
    while i < len(s) and j < len(t):
        result += s[i] + t[j]
        i += 1
        j += 1
    while i < len(s):
        result += s[i]
        i += 1
    while j < len(t):
        result += t[j]
        j += 1
    return result

s = "major"
t = "general"
print(solve(s, t))

The output of the above code is −

mgaejnoerral

Using itertools.zip_longest()

Python provides a more elegant solution using itertools.zip_longest() which handles unequal string lengths automatically −

import itertools

def merge_alternately(s, t):
    result = ""
    for char_s, char_t in itertools.zip_longest(s, t, fillvalue=""):
        result += char_s + char_t
    return result

s = "major"
t = "general"
print(merge_alternately(s, t))

The output of the above code is −

mgaejnoerral

Comparison

Method Time Complexity Space Complexity Best For
Two Pointers O(m + n) O(m + n) Learning algorithm basics
zip_longest() O(m + n) O(m + n) Clean, readable code

Conclusion

Both approaches merge strings alternately with O(m + n) time complexity. Use the two-pointer method for educational purposes or zip_longest() for cleaner production code.

Updated on: 2026-03-25T20:50:00+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements