String Interleaving in Python


Suppose we have two strings s and t, we have to find two strings interleaved, starting with first string s. If there are leftover characters in a string they will be added to the end.

So, if the input is like s = "abcd", t = "pqrstu", then the output will be "apbqcrdstu"

To solve this, we will follow these steps −

  • res:= blank string
  • i:= 0
  • m:= minimum of size of s, size of t
  • while i < m, do
    • res := res concatenate s[i] concatenate t[i]
    • i := i + 1
  • return res concatenate s[from index i to end] concatenate t [from index i to end]

Example

 Live Demo

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:]
ob = Solution()
s = "abcd"
t = "pqrstu"
print(ob.solve(s,t))

Input

"abcd","pqrstu"

Output

apbqcrdstu

Updated on: 23-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements