Program to create a lexically minimal string from two strings in python


Suppose, we have two strings. We want to make a lexically minimum string from those strings. To make the string we compare the first letter of the two strings and extract the lexically smaller letter from one of the strings. In the case of a tie i.e, the letters are the same; we extract the letter from the first string. We repeat this process until both the strings are empty. The minimal string constructed has to be returned.

So, if the input is like input_1 = 'TUTORIALS', input_2 = 'POINT', then the output will be POINTTUTORIALS

If we compare the two strings, we get this step-by-step −

TUTORIALS POINT
TUTORIALS OINT = P
TUTORIALS INT = PO
TUTORIALS NT = POI
TUTORIALS T = POIN
TUTORIALS = POINT

As one of the strings is empty, the whole first string now gets placed in the resultant minimum string. So, the final string is POINTTUTORIALS.

To solve this, we will follow these steps −

  • input_1 := input_1 + "z"
  • input_2 := input_2 + "z"
  • temp_1 := 0
  • temp_2 := 0
  • res_str := blank string
  • while temp_1 < size of input_1 and temp_2 < size of input_2, do
    • if input_1[from index temp_1 to end of the string] < input_2[from index temp_2 to end of the string], then
      • res_str := res_str + input_1[temp_1]
      • temp_1 := temp_1 + 1
    • otherwise,
      • res_str := res_str + input_2[temp_2]
      • temp_2 := temp_2 + 1
  • res_str := res_str[from index 0 to the second last element of the string]
  • if temp_1 < length of (input_1), then
    • res_str := res_str + input_1[from index temp_1 to the second last element of the string]
  • if temp_2 < length of (input_2), then
    • res_str := res_str + input_2[from index temp_2 to the second last element of the string]
  • return res_str

Example

Let us see the following implementation to get better understanding −

def solve(input_1, input_2):
   input_1 += "z"
   input_2 += "z"
   temp_1 = 0
   temp_2 = 0
   res_str = ""
   while temp_1 < len(input_1) and temp_2 < len(input_2):
      if input_1[temp_1:] < input_2[temp_2:]:
         res_str += input_1[temp_1]
         temp_1 += 1
      else:
         res_str += input_2[temp_2]
         temp_2 += 1
   res_str = res_str[:-1]
   if temp_1 < len(input_1):
      res_str += input_1[temp_1:-1]
   if temp_2 < len(input_2):
      res_str += input_2[temp_2:-1]
   return res_str

print(solve('TUTORIALS', 'POINT'))

Input

'TUTORIALS', 'POINT'

Output

POINTTUTORIALS

Updated on: 09-Oct-2021

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements