String Interleaving in Python

String interleaving combines two strings by alternating characters from each string, starting with the first string. If one string is longer, the remaining characters are appended to the end.

For example, if we have s = "abcd" and t = "pqrstu", the interleaved result will be "apbqcrdstu".

Algorithm Steps

To solve this problem, we follow these steps ?

  • Initialize an empty result string
  • Find the minimum length between both strings
  • Iterate up to the minimum length, alternating characters from each string
  • Append any remaining characters from the longer string

Using a Class Method

Here's the implementation using a class-based approach ?

class Solution:
    def solve(self, s, t):
        res = ""
        i = 0
        m = min(len(s), len(t))
        while i < m:
            res += s[i] + t[i]
            i += 1
        return res + s[i:] + t[i:]

# Test the solution
ob = Solution()
s = "abcd"
t = "pqrstu"
print(ob.solve(s, t))
apbqcrdstu

Using a Simple Function

We can also implement this as a standalone function ?

def interleave_strings(s, t):
    result = ""
    min_len = min(len(s), len(t))
    
    # Interleave characters up to minimum length
    for i in range(min_len):
        result += s[i] + t[i]
    
    # Add remaining characters
    result += s[min_len:] + t[min_len:]
    return result

# Test with different examples
print(interleave_strings("abc", "xyz"))
print(interleave_strings("hello", "world123"))
print(interleave_strings("short", "verylongstring"))
axbycz
hweolrllod123
svheorrylt ongstring

How It Works

The algorithm works by:

  • Finding the overlap: Determine how many characters can be interleaved by taking the minimum length
  • Character alternation: For each position up to the minimum length, take one character from each string
  • Appending remainder: Add any leftover characters from the longer string to the end

Time and Space Complexity

The time complexity is O(m + n) where m and n are the lengths of the input strings. The space complexity is O(m + n) for storing the result string.

Conclusion

String interleaving is accomplished by alternating characters from two strings up to the shorter string's length, then appending any remaining characters. This technique is useful for merging sequences while maintaining the relative order of elements.

Updated on: 2026-03-25T10:25:27+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements