Merge Two Sorted Strings Lexicographically
In this lesson, we will learn how to merge two strings lexicographically.
We'll cover the following
What does “Merging Two Sorted Strings Lexicographically” Mean?
Lexicographical means according to the alphabetical order.
Lower case letters are different from upper case letters, therefore, they are treated differently. Also, all upper case letters come before all lower case letters. Alphabetic sorting is as follows:
Implementation
def merge(string1, string2) :# Base Case1if string1 == "" :if string2 == "" :return ""return string2# Base Case2elif string2 == "" :return string1# Recursive Case1elif string1[0] > string2[0] :return string2[0] + merge(string1, string2[1:])# Recursive Case2return string1[0] + merge(string1[1:], string2)# Driver Codestring1 = "acu"string2 = "bst"print(merge(string1, string2))
Explanation
The two strings passed, in this case, string1
and string2
to the function merge()
are sorted.
The characters in the two strings may satisfy of the conditions:
-
Both
string1
andstring2
are equal to an empty string""
.- In this case return
""
.
- In this case return
-
string1 == ""
therefore, returnstring2
. -
string2 == ""
therefore, returnstring1
.
These conditions will be the base case. Here no string manipulation is occurring. We just return the specific string.
-
The first element of
string1
is greater than the first element ofstring2
.In Python, an alphabet can be compared with another alphabet. This means that
a < b
,b < c
,c < d
and so on.- In this case, save the first element of
string2
since it is smaller. Then recursively call another instance ofmerge()
with that element removed.
- In this case, save the first element of
-
The first element of
string1
is less than the first element ofstring2
.- In this case, save the first element of
string1
since it is smaller. Then recursively call another instance ofmerge()
with that element removed.
- In this case, save the first element of
Let’s have a look at an illustration:
In the next lesson, we have a challenge for you to solve.