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

PythonServer Side ProgrammingProgramming

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


Let us see the following implementation to get better understanding −

 Live Demo

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
   if (minimum_index != 10**9):
      return Str[minimum_index]
      return -1
Str = "helloworld"
patt = "wor"
print(get_min_index_char(Str, patt))


"helloworld", "wor"


Published on 19-Aug-2020 15:00:51