Program to find largest merge of two strings in Python



Suppose we have two strings s and t. We want to form 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.

Finally, we have to find the lexicographically largest merge that we can form.

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

To solve this, we will follow these steps −

  • a := 0, b := 0

  • merge := blank string

  • W1 := size of s

  • W2 := size of t

  • while a < W1 and b < W2, do

    • if substring of s from index a to end > substring of t from index b to end, then

      • merge := merge concatenate s[a]

      • a := a + 1

    • otherwise,

      • merge := merge concatenate t[b]

      • b := b + 1

  • return merge concatenate (substring of s from index a to end) concatenate (substring of t from index b to end)

Example

Let us see the following implementation to get better understanding −

def solve(s, t):
   a = b = 0
   merge = ""

   W1 = len(s)
   W2 = len(t)
   while a < W1 and b < W2:
      if s[a:] > t[b:]:
         merge += s[a]
         a += 1
      else:
         merge += t[b]
         b += 1

   return merge + s[a:] + t[b:]

s = "zxyxx"
t = "yzxxx"
print(solve(s, t))

Input

"zxyxx", "yzxxx"

Output

zyzxyxxxxx

Advertisements