Largest Merge of Two Strings in Python


Let us suppose we have two strings 'a' and 'b' and a string 'merge'. The task is to fill the string 'merge' with the characters from 'a' and 'b' in such a way that,

  • If the string 'a' is non-empty, then remove the first character from the string 'a' and copy it into string 'merge'.
  • If the string 'b' is non-empty, then remove the first character from the string 'b' and copy it into string 'merge'.
  • If the strings 'a' and 'b' are non-empty, then remove the first characters from string 'a' and copy it into string 'merge' and then remove the first character (if any) from string 'b' and copy it into the string 'merge'.
  • Remove the characters from both the strings lexicographically, which means, if string 'a' is greater than string 'b', then remove the character from string 'a' and then string 'b'.
  • Return the string 'merge'.

For Example

Input-1: 

a = “bacaa”

b = “abcaa”

Output:

babcacaaaa

Explanation:

Since the given string 'a' is lexicographically greater than the string 'b', we will extract the first character from string 'a', i.e., “b” and then from string 'b'. After extracting, the string will be “babcacaaaa”.

Approach to solve this Problem

The recursive approach to solve this problem is that we will extract each character of string 'a' and string 'b' and will check if the characters of string 'a' are lexicographically greater than the other string and finally concatenate to string 'merge'.

We will find the substring of each character after a number of positions and concatenate into 'merge' if it is lexicographically greater than the other string.

  • Take two input strings 'a' and 'b'.
  • A recursive string function concatenateLargest(string a, string b) takes two strings as the input and returns the largest string after concatenation, i.e., (string 'a' + string 'b').
  • If 'a > b', then split string 'a' with position '0' and return the output from string 'a'.
  • If 'a < b', then split string 'b' with position '0' and return the output from string 'b'.
  • Return the concatenated string.

Example

def concatenateLargest(a, b):
   ans = ""
   while a and b:
      if a > b:
         ans = a[0]
         a = a[1:]
      else:
         ans = b[0]
         b = b[1:]
   ans = a
   ans = b
   return ans
a = "bacaa"
b = "abcaa"
print(concatenateLargest(a, b))

Running the above code will generate the output as,

Output

bacabcaaaa

The two strings “bacaa” and “abcaa” will become “bacabcaaaa” after merging according to the given problem.

Updated on: 23-Feb-2021

149 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements