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

01 May, 2021
Given a string str and another string patt. 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 ‘No character present’.
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: No character present
Source: OLA Interview Experience | Set 12.
Naive Approach: Using two loops, find the first index of each character of patt in str. Print the character having the minimum index. If no character of patt is present in str then print “No character present”.
C++
Java
Python3
C#
Javascript
// C++ implementation to find the character in// first string that is present at minimum index// in second string#include <bits/stdc++.h>using namespace std; // function to find the minimum index charactervoid printMinIndexChar(string str, string patt){    // to store the index of character having    // minimum index    int minIndex = INT_MAX;     // lengths of the two strings    int m = str.size();    int n = patt.size();     // traverse 'patt'    for (int i = 0; i < n; i++) {         // for each character of 'patt' traverse 'str'        for (int j = 0; j < m; j++) {             // if patt[i] is found in 'str', check if            // it has the minimum index or not. If yes,            // then update 'minIndex' and break            if (patt[i] == str[j] && j < minIndex) {                minIndex = j;                break;            }        }    }     // print the minimum index character    if (minIndex != INT_MAX)        cout << "Minimum Index Character = "             << str[minIndex];     // if no character of 'patt' is present in 'str'    else        cout << "No character present";} // Driver program to test aboveint main(){    string str = "geeksforgeeks";    string patt = "set";    printMinIndexChar(str, patt);    return 0;}
// Java implementation to find the character in// first string that is present at minimum index// in second string public class GFG{    // method to find the minimum index character    static void printMinIndexChar(String str, String patt)    {        // to store the index of character having        // minimum index        int minIndex = Integer.MAX_VALUE;              // lengths of the two strings        int m = str.length();        int n = patt.length();              // traverse 'patt'        for (int i = 0; i < n; i++) {                  // for each character of 'patt' traverse 'str'            for (int j = 0; j < m; j++) {                      // if patt.charAt(i)is found in 'str', check if                // it has the minimum index or not. If yes,                // then update 'minIndex' and break                if (patt.charAt(i)== str.charAt(j) && j < minIndex) {                    minIndex = j;                    break;                }            }        }              // print the minimum index character        if (minIndex != Integer.MAX_VALUE)            System.out.println("Minimum Index Character = " +                                str.charAt(minIndex));              // if no character of 'patt' is present in 'str'        else            System.out.println("No character present");    }         // Driver Method    public static void main(String[] args)    {        String str = "geeksforgeeks";        String patt = "set";        printMinIndexChar(str, patt);    }}
# Python3 implementation to find the character in# first that is present at minimum index# in second String # function to find the minimum index characterdef printMinIndexChar(Str, patt):     # to store the index of character having    # minimum index    minIndex = 10**9     # lengths of the two Strings    m =len(Str)    n =len(patt)     # traverse 'patt'    for i in range(n):         # for each character of 'patt' traverse 'Str'        for j in range(m):             # if patt[i] is found in 'Str', check if            # it has the minimum index or not. If yes,            # then update 'minIndex' and break            if (patt[i] == Str[j] and j < minIndex):                minIndex = j                break        # print the minimum index character    if (minIndex != 10**9):        print("Minimum Index Character = ",Str[minIndex])     # if no character of 'patt' is present in 'Str'    else:        print("No character present")  # Driver code Str = "geeksforgeeks"patt = "set"printMinIndexChar(Str, patt) # This code is contributed by mohit kumar 29
// C# implementation to find the character in// first string that is present at minimum index// in second stringusing System; class GFG{    // method to find the minimum index character    static void printMinIndexChar(String str, String patt)    {        // to store the index of character having        // minimum index        int minIndex = int.MaxValue;             // lengths of the two strings        int m = str.Length;        int n = patt.Length;             // traverse 'patt'        for (int i = 0; i < n; i++) {                 // for each character of 'patt' traverse 'str'            for (int j = 0; j < m; j++) {                     // if patt.charAt(i)is found in 'str', check if                // it has the minimum index or not. If yes,                // then update 'minIndex' and break                if (patt[i]== str[j] && j < minIndex) {                    minIndex = j;                    break;                }            }        }             // print the minimum index character        if (minIndex != int.MaxValue)            Console.WriteLine("Minimum Index Character = " +                                str[minIndex]);             // if no character of 'patt' is present in 'str'        else            Console.WriteLine("No character present");    }         // Driver Methoda    public static void Main()    {        String str = "geeksforgeeks";        String patt = "set";        printMinIndexChar(str, patt);    }}// This code is contributed by Sam007
<script>// Javascript implementation to find the character in// first string that is present at minimum index// in second string         // method to find the minimum index character    function printMinIndexChar(str,patt)    {        // to store the index of character having        // minimum index        let minIndex = Number.MAX_VALUE;                // lengths of the two strings        let m = str.length;        let n = patt.length;                // traverse 'patt'        for (let i = 0; i < n; i++) {                    // for each character of 'patt' traverse 'str'            for (let j = 0; j < m; j++) {                        // if patt.charAt(i)is found in 'str', check if                // it has the minimum index or not. If yes,                // then update 'minIndex' and break                if (patt[i]== str[j] && j < minIndex) {                    minIndex = j;                    break;                }            }        }                // print the minimum index character        if (minIndex != Number.MAX_VALUE)            document.write("Minimum Index Character = " +                                str[minIndex]);                // if no character of 'patt' is present in 'str'        else            document.write("No character present");    }         // Driver Method    let str = "geeksforgeeks";    let patt = "set";    printMinIndexChar(str, patt);         //This code is contributed by rag2127     </script>
Output:  
Minimum Index Character = e
Time Complexity: O(mn), where m and n are the lengths of the two strings. Auxiliary Space: O(1) Method 2 Efficient Approach(Hashing):  
Create a hash table with (key, value) tuple represented as (character, index) tuple.
Store the first index of each character of str in the hash table.
Now, for each character of patt check if it is present in the hash table or not. If present then get its index from the hash table and update minIndex(minimum index encountered so far).For no matching character print “No character present”.
If present then get its index from the hash table and update minIndex(minimum index encountered so far).
For no matching character print “No character present”.
Hash table is implemented using unordered_set in C++.The below image is a dry run of the above approach: 
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the character in first// string that is present at minimum index in second// string#include <bits/stdc++.h>using namespace std; // function to find the minimum index charactervoid printMinIndexChar(string str, string patt){    // unordered_map 'um' implemented as hash table    unordered_map<char, int> um;     // to store the index of character having    // minimum index    int minIndex = INT_MAX;     // lengths of the two strings    int m = str.size();    int n = patt.size();-     // store the first index of each character of 'str'    for (int i = 0; i < m; i++)        if (um.find(str[i]) == um.end())            um[str[i]] = i;     // traverse the string 'patt'    for (int i = 0; i < n; i++)         // if patt[i] is found in 'um', check if        // it has the minimum index or not accordingly        // update 'minIndex'        if (um.find(patt[i]) != um.end() &&            um[patt[i]] < minIndex)            minIndex = um[patt[i]];     // print the minimum index character    if (minIndex != INT_MAX)        cout << "Minimum Index Character = "             << str[minIndex];     // if no character of 'patt' is present in 'str'    else        cout << "No character present";} // Driver program to test aboveint main(){    string str = "geeksforgeeks";    string patt = "set";    printMinIndexChar(str, patt);    return 0;}
// Java implementation to find the character in// first string that is present at minimum index// in second string import java.util.HashMap; public class GFG{    // method to find the minimum index character    static void printMinIndexChar(String str, String patt)    {        // map to store the first index of each character of 'str'        HashMap<Character, Integer> hm = new HashMap<>();                 // to store the index of character having        // minimum index        int minIndex = Integer.MAX_VALUE;              // lengths of the two strings        int m = str.length();        int n = patt.length();              // store the first index of each character of 'str'        for (int i = 0; i < m; i++)            if(!hm.containsKey(str.charAt(i)))                hm.put(str.charAt(i),i);              // traverse the string 'patt'        for (int i = 0; i < n; i++)            // if patt[i] is found in 'um', check if            // it has the minimum index or not accordingly            // update 'minIndex'            if (hm.containsKey(patt.charAt(i)) &&                hm.get(patt.charAt(i)) < minIndex)                minIndex = hm.get(patt.charAt(i));              // print the minimum index character        if (minIndex != Integer.MAX_VALUE)            System.out.println("Minimum Index Character = " +                                str.charAt(minIndex));              // if no character of 'patt' is present in 'str'        else            System.out.println("No character present");    }         // Driver Method    public static void main(String[] args)    {        String str = "geeksforgeeks";        String patt = "set";        printMinIndexChar(str, patt);    }}
# Python3 implementation to# find the character in first# string that is present at# minimum index in second stringimport sys # Function to find the# minimum index characterdef printMinIndexChar(st, patt):     # unordered_map 'um'    # implemented as hash table    um = {}     # to store the index of    # character having minimum index    minIndex = sys.maxsize     # Lengths of the two strings    m = len(st)    n = len(patt)     # Store the first index of    # each character of 'str'    for i in range (m):        if (st[i] not in um):            um[st[i]] = i     # traverse the string 'patt'    for i in range(n):         # If patt[i] is found in 'um',        # check if  it has the minimum        # index or not accordingly        # update 'minIndex'        if (patt[i] in um and            um[patt[i]] < minIndex):            minIndex = um[patt[i]]     # Print the minimum index character    if (minIndex != sys.maxsize):        print ("Minimum Index Character = ",                st[minIndex])     # If no character of 'patt'    # is present in 'str'    else:        print ("No character present") # Driver program to test aboveif __name__ == "__main__":   st = "geeksforgeeks"  patt = "set"  printMinIndexChar(st, patt) # This code is contributed by Chitranayal
// C# implementation to find the character in// first string that is present at minimum index// in second stringusing System;using System.Collections.Generic; class GFG{    // method to find the minimum index character    static void printMinIndexChar(String str, String patt)    {        // map to store the first index of        // each character of 'str'        Dictionary<char,                   int> hm = new Dictionary<char,                                            int>();                 // to store the index of character having        // minimum index        int minIndex = int.MaxValue;             // lengths of the two strings        int m = str.Length;        int n = patt.Length;             // store the first index of        // each character of 'str'        for (int i = 0; i < m; i++)            if(!hm.ContainsKey(str[i]))                hm.Add(str[i], i);             // traverse the string 'patt'        for (int i = 0; i < n; i++)                     // if patt[i] is found in 'um',            // check if it has the minimum index            // or not, accordingly update 'minIndex'            if (hm.ContainsKey(patt[i]) &&                hm[patt[i]] < minIndex)                minIndex = hm[patt[i]];             // print the minimum index character        if (minIndex != int.MaxValue)            Console.WriteLine("Minimum Index Character = " +                                             str[minIndex]);             // if no character of 'patt' is present in 'str'        else            Console.WriteLine("No character present");    }         // Driver Code    public static void Main(String[] args)    {        String str = "geeksforgeeks";        String patt = "set";        printMinIndexChar(str, patt);    }} // This code is contributed by Princi Singh
<script> // Javascript implementation to find the// character in first string that is// present at minimum index in second// string     // Method to find the minimum index characterfunction  printMinIndexChar(str, patt){         // map to store the first index of    // each character of 'str'    let hm = new Map();          // To store the index of character having    // minimum index    let minIndex = Number.MAX_VALUE;       // Lengths of the two strings    let m = str.length;    let n = patt.length;       // Store the first index of    // each character of 'str'    for(let i = 0; i < m; i++)        if (!hm.has(str[i]))            hm.set(str[i], i);       // Traverse the string 'patt'    for(let i = 0; i < n; i++)             // If patt[i] is found in 'um', check        // if it has the minimum index or not        // accordingly update 'minIndex'        if (hm.has(patt[i]) &&            hm.get(patt[i]) < minIndex)            minIndex = hm.get(patt[i]);       // Print the minimum index character    if (minIndex != Number.MAX_VALUE)        document.write("Minimum Index Character = " +                       str[minIndex]);       // If no character of 'patt' is    // present in 'str'    else        document.write("No character present");} // Driver Codelet str = "geeksforgeeks";let patt = "set"; printMinIndexChar(str, patt); // This code is contributed by avanitrachhadiya2155     </script>
Output: 
Minimum Index Character = e
Time Complexity: O(m + n), where m and n are the lengths of the two strings. Auxiliary Space: O(d), where d is the size of hash table, which is the count of distinct characters in str.  
Minimum Index Character | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMinimum Index Character | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=6nWWUYNnpXM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
mohit kumar 29
princi singh
ManasChhabra2
nidhi_biet
ukasp
rag2127
avanitrachhadiya2155
Ola Cabs
STL
Hash
Strings
Ola Cabs
Hash
Strings
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find k numbers with most occurrences in the given array
Real-time application of Data Structures
Non-Repeating Element
Find the length of largest subarray with 0 sum
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack