VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-character-first-string-present-minimum-index-second-string/

⇱ Find Minimum Indexed Character in String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Minimum Indexed Character in String

Last Updated : 13 Aug, 2024

Given a string str and another string patt. The task is to find the character in patt that is present at the minimum index in str. If no character of patt is present in str then print "$".

Examples

Input: str = "geeksforgeeks", patt = "set" 
Output: e 
Both e and s of patt are present in str, but e is present at minimum index, which is 1.

Input: str = "adcffaet", patt = "onkl" 
Output: -1

Source:OLA Interview Experience

[Naive Approach] Using Two Nested Loops - O(m*n) Time and O(1) Space

The very simple approach to solve this problem is that we can use two nested loops: The outer loop goes through each character in str one by one. For each character in str, the inner loop checks if this character exists in patt. As soon as we find a match (i.e., a character in str that is also in patt), we return that character because it's the first character from patt that appears in str. If no match is found after checking all characters, we return "$" to indicate that no characters from patt are present in str.

Below is the implementation of above approach:


Output
e

Time Complexity: O(m*n), where m and n are the lengths of the two strings. 
Auxiliary Space: O(1) 

[Expected Approach] Using Frequency Array - O(n) Time and O(1) Space

The idea is to create a frequency array of size 26, corresponding to each letter of the alphabet. This will count how many times each character appears in the patt. Then, iterates through str and check for each character against the frequency array. The first character found in str with a non-zero frequency indicates it is present in patt, and this character is returned. If no match is found, returns a special character ($).


Output
e

Time Complexity: O(n), where n is the length of given string str
Auxiliary Space: O(1)

[Other Approach] Using Set or Hashing - O(n) Time and O(1) space

This idea is similar to the above discussed approach, instead of using frequency array of size 26, we can use any data structure like set or hash map. The idea it that first storing all characters from the pattern (patt) in a set or hash map, allowing for quick lookups. Then, iterates through the main string (str) to find the first character that exists in the set or hash map. If such character found then, this character is the one that appears at the minimum index in str and is also present in patt. If no such character is found, it returns "$" to indicate that none of the characters in patt are present in str

Below is the implementation of the above approach:


Output
e

Time Complexity: O(m + n), where m and n are the lengths of the two strings. 
Auxiliary Space: O(1)

Comment
Article Tags: