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
  • if input_1[from index temp_1 to end of the string]
  • 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
  • res_str := res_str + input_1[from index temp_1 to the second last element of the string]
  • if temp_2
  • 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 

    Input

    'TUTORIALS', 'POINT'

    Output

    POINTTUTORIALS
    
    Updated on: 2021-10-09T11:29:37+05:30

    201 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements