Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 need to find the character in patt that is present at the minimum index in str. If no character from patt is present in str, then return -1.
For example, if str = "helloworld" and patt = "wor", the output will be 'o' because 'o' appears at index 4, which is the smallest index among all characters from patt that exist in str.
Algorithm Steps
To solve this problem, we follow these steps ?
Initialize
minimum_indexto a large valueFor each character in
patt, find its first occurrence instrKeep track of the minimum index found so far
Return the character at minimum index, or
-1if no character is found
Implementation
Let us see the implementation to get better understanding ?
def get_min_index_char(str_input, patt):
minimum_index = 10**9
for i in range(len(patt)):
for j in range(len(str_input)):
if (patt[i] == str_input[j] and j < minimum_index):
minimum_index = j
break
if (minimum_index != 10**9):
return str_input[minimum_index]
else:
return -1
# Test the function
str_input = "helloworld"
patt = "wor"
result = get_min_index_char(str_input, patt)
print(f"Character at minimum index: {result}")
The output of the above code is ?
Character at minimum index: o
How It Works
In the example above:
'w'is found at index 5 in "helloworld"'o'is found at index 4 in "helloworld"'r'is found at index 8 in "helloworld"
Since index 4 is the minimum among these positions, the function returns 'o'.
Alternative Approach Using Built-in Methods
We can also solve this using Python's find() method for a more concise solution ?
def get_min_index_char_optimized(str_input, patt):
min_index = float('inf')
min_char = -1
for char in patt:
index = str_input.find(char)
if index != -1 and index < min_index:
min_index = index
min_char = char
return min_char
# Test the optimized function
str_input = "helloworld"
patt = "wor"
result = get_min_index_char_optimized(str_input, patt)
print(f"Character at minimum index: {result}")
The output of the above code is ?
Character at minimum index: o
Conclusion
Both approaches solve the problem effectively. The first method uses nested loops for explicit searching, while the second uses Python's built-in find() method for cleaner code. Choose the approach that best fits your coding style and requirements.
