Computer >> Computer tutorials >  >> Programming >> Python

Find the character in first string that is present at minimum index in second string in Python


Suppose we have a string str and another string patt, we have to find determine the character in patt that is present at the minimum index of str. If no character patt1 is present in str1 then return -1.

So, if the input is like str = "helloworld" and patt = "wor", then the output will be 'o' as 'o' is present at minimum index in str

To solve this, we will follow these steps −

  • for i in range 0 to size of patt, do

    • for j in range 0 to size of Str, do

      • if patt[i] is same as Str[j] and j < minimum_index, then

        • minimum_index := j

        • come out from the loop

  • if minimum_index is not same as 10^9 , then

    • return Str[minimum_index]

  • otherwise,

    • return -1

Example 

Let us see the following implementation to get better understanding −

def get_min_index_char(Str, patt):
   minimum_index = 10**9
   for i in range(len(patt)):
      for j in range(len(Str)):
         if (patt[i] == Str[j] and j < minimum_index):
            minimum_index = j
            break
   if (minimum_index != 10**9):
      return Str[minimum_index]
   else:
      return -1
Str = "helloworld"
patt = "wor"
print(get_min_index_char(Str, patt))

Input

"helloworld", "wor"

Output

o