• If s is non-empty, then append the first cha">

    Program to get maximum length merge of two given strings in Python



    Suppose we have two strings s and t. We have to make a string called merge in the following way: while either s or t are non-empty, select one of the following options −

    • If s is non-empty, then append the first character in s to merge and delete it from s.

    • If t is non-empty, then append the first character in t to merge and delete it from t.

    So we have to find the lexicographically largest merge we can make.

    So, if the input is like s = "zxyxx" t = "yzxxx", then the output will be zyzxyxxxxx, because

    • Pick from s: merge = "z", s = "xyxx", t = "yzxxx"

    • Pick from t: merge = "zy", s = "xyxx", t = "zxxx"

    • Pick from t: merge = "zyz", s = "xyxx", t = "xxx"

    • Pick from s: merge = "zyzx", s = "yxx", t = "xxx"

    • Pick from s: merge = "zyzxy", s = "xx", t = "xxx"

    Then add the remaining 5 x's from s and t at the end of merge.

    To solve this, we will follow these steps −

    • ans := blank string

    • idx1 := 0, idx2 := 0

    • while idx1 < size of s and idx2 < size of t, do

      • if s[idx1] > t[idx2] or (s[idx1] is same as t[idx2] and substring of s[from index idx1 to end] >= substring of t[from index idx2 to end]), then

        • ans := ans concatenate s[idx1]

        • idx1 := idx1 + 1

      • otherwise when s[idx1] < t[idx2] or (s[idx1] is same as t[idx2] and substring of s[from index idx1 to end] <= substring of t[from index idx2 to end]), then

        • ans := ans concatenate t[idx2]

        • idx2 := idx2 + 1

    • return ans concatenate s[from index idx1 to end] concatenate t[from index idx2 to end]

    Example

    Let us see the following implementation to get better understanding −

    def solve(s, t):
       ans = ""
       idx1 = idx2 = 0
       while(idx1<len(s) and idx2<len(t)):
          if s[idx1]>t[idx2] or (s[idx1]==t[idx2] and s[idx1:]>=t[idx2:]):
             ans+=s[idx1]
             idx1+=1
          elif s[idx1]<t[idx2] or (s[idx1]==t[idx2] and s[idx1:]<=t[idx2:]):
             ans+=t[idx2]
             idx2+=1
    
       return ans+s[idx1:]+t[idx2:]
    
    s = "zxyxx"
    t = "yzxxx"
    print(solve(s, t))
    
    

    Input

    [7,4,5,3,8], [[0,2,2],[4,2,4],[2,13,100]]

    Output

    zyzxyxxxxx
    
    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements