Open In App

Find Minimum Indexed Character in String

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to print the minimum index character
// in a string.
string findMinIndexChar(const string &S, 
                        const string &patt) {
  
    // Iterate over each character in S
    for (int i = 0; i < S.length(); i++) {
      
        // For each character in S, iterate over
        // each character in patt
        for (int j = 0; j < patt.length(); j++) {
          
            // If a character in S matches a character 
            // in patt
            if (S[i] == patt[j]) {
              
                // Return the matched character
                return string(1, S[i]);
            }
        }
    }
    // If no match is found, return '$'
    return "$";
}

int main() {
    string S = "geeksforgeeks";
    string patt = "set";
    string result = findMinIndexChar(S, patt);
    cout << result;

    return 0;
}
C
#include <stdio.h>
#include <string.h>

// Function to print the minimum index character
// in a string.
char findMinIndexChar(const char *S, 
                      const char *patt) {

    // Iterate over each character in S
    for (int i = 0; S[i] != '\0'; i++) {
      
        // For each character in S, iterate over
        // each character in patt
        for (int j = 0; patt[j] != '\0'; j++) {
          
            // If a character in S matches a character 
            // in patt
            if (S[i] == patt[j]) {
              
                // Return the matched character
                return S[i];
            }
        }
    }
    // If no match is found, return '$'
    return '$';
}

int main() {
    char S[] = "geeksforgeeks";
    char patt[] = "set";
    char result = findMinIndexChar(S, patt);
    printf("%c\n", result);

    return 0;
}
Java
import java.util.*;

class GfG {

    // Function to print the minimum index character
    // in a string.
    static String findMinIndexChar(String S, 
                                   String patt) {
      
        // Iterate over each character in S
        for (int i = 0; i < S.length(); i++) {
          
            // For each character in S, iterate over
            // each character in patt
            for (int j = 0; j < patt.length(); j++) {
              
                // If a character in S matches a character 
                // in patt
                if (S.charAt(i) == patt.charAt(j)) {
                  
                    // Return the matched character
                    return String.valueOf(S.charAt(i));
                }
            }
        }
        // If no match is found, return "$"
        return "$";
    }

    public static void main(String[] args) {
        String S = "geeksforgeeks";
        String patt = "set";
        String result = findMinIndexChar(S, patt);
        System.out.println(result);
    }
}
Python
# Function to print the minimum index character
# in a string.
def find_min_index_char(S, patt):
    
    # Iterate over each character in S
    for i in range(len(S)):
        
        # For each character in S, iterate over
        # each character in patt
        for j in range(len(patt)):
            
            # If a character in S matches a character 
            # in patt
            if S[i] == patt[j]:
                
                # Return the matched character
                return S[i]
    
    # If no match is found, return '$'
    return '$'

S = "geeksforgeeks"
patt = "set"
result = find_min_index_char(S, patt)
print(result)
C#
using System;

class GfG {
    
    // Function to print the minimum index character
    // in a string.
    static string FindMinIndexChar(string S, 
                                   string patt) {
        
        // Iterate over each character in S
        for (int i = 0; i < S.Length; i++) {
            
            // For each character in S, iterate over
            // each character in patt
            for (int j = 0; j < patt.Length; j++) {
                
                // If a character in S matches a character 
                // in patt
                if (S[i] == patt[j]) {
                    
                    // Return the matched character
                    return S[i].ToString();
                }
            }
        }
        // If no match is found, return "$"
        return "$";
    }

    static void Main(string[] args) {
        string S = "geeksforgeeks";
        string patt = "set";
        string result = FindMinIndexChar(S, patt);
        Console.WriteLine(result);
    }
}
JavaScript
// Function to print the minimum index character
// in a string.
function findMinIndexChar(S, patt) {
  
    // Iterate over each character in S
    for (let i = 0; i < S.length; i++) {
      
        // For each character in S, iterate over
        // each character in patt
        for (let j = 0; j < patt.length; j++) {
          
            // If a character in S matches a character 
            // in patt
            if (S[i] === patt[j]) {
              
                // Return the matched character
                return S[i];
            }
        }
    }
    // If no match is found, return '$'
    return '$';
}

const S = "geeksforgeeks";
const patt = "set";
const result = findMinIndexChar(S, patt);
console.log(result);

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 ($).

C++
#include <bits/stdc++.h>
using namespace std;

// Function to print the minimum index character
// in a string.
string printMinIndexChar(string & str, string & patt) {
    // Creating a vector of size 26 to maintain
    // frequency of characters in patt.
    vector<int> hash(26, 0);
    
    // Iterating over each character in patt
    // and updating its frequency.
    for (auto i : patt) 
        hash[i - 'a']++;

    // Iterating over each character in str.
    for (auto i : str) {
      
        // If frequency of current character
        // in str is non-zero, we have found
        // the minimum index character.
        if (hash[i - 'a']) {
          return string(1, i);
        }
    }

    // If no minimum index character found
    return "$";
}

int main() {
    string str = "geeksforgeeks"; 
    string patt = "set";
    string result = printMinIndexChar(str, patt);
    cout << result << endl; 
    return 0;
}
C
#include <stdio.h>
#include <string.h>

// Function to print the minimum index character
// in a string.
char* printMinIndexChar(char *str, char *patt) {
    // Creating an array of size 26 to maintain
    // frequency of characters in patt.
    int hash[26] = {0};

    // Iterating over each character in patt
    // and updating its frequency.
    for (int i = 0; patt[i] != '\0'; i++) {
        hash[patt[i] - 'a']++;
    }

    // Iterating over each character in str.
    for (int i = 0; str[i] != '\0'; i++) {
        // If frequency of current character in str 
        // is non-zero, we have found the minimum
        // index character.
        if (hash[str[i] - 'a'] > 0) {
          
           // Creating a static array to store the answer.
            static char ans[2];
            ans[0] = str[i]; 
            ans[1] = '\0'; 
            return ans; 
        }
    }

    // If no minimum index character found
    return "$";
}

int main() {
    char str[] = "geeksforgeeks"; 
    char patt[] = "set"; 
    char *result = printMinIndexChar(str, patt); 
    printf("%s\n", result);
    return 0;
}
Java
class GfG {
    // Function to print the minimum index character in a
    // string.
    static char printMinIndexChar(String str,
                                         String patt)
    {
        // Creating an array to maintain frequency of
        // characters in patt.
        int[] hash = new int[26];

        // Iterating over each character in patt and
        // updating its frequency.
        for (char c : patt.toCharArray()) {
            hash[c - 'a']++;
        }

        // Iterating over each character in str.
        for (char c : str.toCharArray()) {
            // If frequency of current character in str is
            // non-zero, we have found the minimum index
            // character.
            if (hash[c - 'a'] > 0) {
              // Returning the minimum index
              // character.
                return c; 
            }
        }

        // If no minimum index character found
        return '$';
    }

    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        String patt = "set"; 
        char result = printMinIndexChar(
            str, patt); 
        System.out.println(result); 
    }
}
Python
def print_min_index_char(str, patt):
    # Creating a list to maintain frequency
    # of characters in patt.
    hash = [0] * 26

    # Iterating over each character in patt
    # and updating its frequency.
    for char in patt:
        hash[ord(char) - ord('a')] += 1

    # Iterating over each character in str.
    for char in str:

        # If frequency of current character
        # in str is non-zero, we have found
        # the minimum index character.
        if hash[ord(char) - ord('a')] > 0:
            # Returning the minimum index character.
            return char  

    # If no minimum index character found, return '$'.
    return '$'

if __name__ == "__main__":
    str = "geeksforgeeks" 
    patt = "set"  
    result = print_min_index_char(str, patt)  
    print(result)  
C#
using System;

class GfG {
    // Function to print the minimum index character in a
    // string.
    static char PrintMinIndexChar(string str,
                                         string patt)
    {
        // Creating an array to maintain frequency of
        // characters in patt.
        int[] hash = new int[26];

        // Iterating over each character in patt and
        // updating its frequency.
        foreach(char c in patt) { hash[c - 'a']++; }

        // Iterating over each character in str.
        foreach(char c in str)
        {

            // If frequency of current character in str is
            // non-zero, we have found the minimum index
            // character.
            if (hash[c - 'a'] > 0) {

                // Returning the minimum index character.
                return c;
            }
        }

        // If no minimum index character found, return '$'.
        return '$';
    }

    static void Main()
    {
        string str = "geeksforgeeks"; 
        string patt = "set"; 
        char result = PrintMinIndexChar(
            str, patt);
        Console.WriteLine(result);
    }
}
JavaScript
function printMinIndexChar(str, patt)
{
    // Creating an array to maintain frequency of characters
    // in patt.
    let hash = new Array(26).fill(0);

    // Iterating over each character in patt and updating
    // its frequency.
    for (let char of patt) {
        hash[char.charCodeAt(0) - "a".charCodeAt(0)]++;
    }

    // Iterating over each character in str.
    for (let char of str) {
        // If frequency of current character in str is
        // non-zero, we have found the minimum index
        // character.
        if (hash[char.charCodeAt(0) - "a".charCodeAt(0)]
            > 0) {
            return char; // Returning the minimum index
                         // character.
        }
    }

    // If no minimum index character found, return '$'.
    return "$";
}

const str = "geeksforgeeks"; 
const patt = "set"; 
const result
    = printMinIndexChar(str, patt); 
console.log(result);

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:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to print the minimum index character
// in a string.
string printMinIndexChar(string & str, 
                         string & patt) {
    // Creating an unordered_map to store the characters 
    // of patt as keys and their presence as values.
    unordered_map<char, bool> hash;
    
    // Iterating over each character in patt and 
    // updating its presence.
    for (char ch : patt) 
        hash[ch] = true;

    // Iterating over each character in str.
    for (char ch : str) {
      
        // If current character in str is present
        // in the hash map, we have found the minimum
        // index character.
        if (hash[ch]) {
          
            // Returning the minimum index character
            // as a string.
            return string(1, ch);
        }
    }

    // If no minimum index character found
    return "$";
}

int main() {
    string str = "geeksforgeeks"; 
    string patt = "set";
    string result = printMinIndexChar(str, patt);
    cout << result << endl; 
    return 0;
}
Java
import java.util.*;

// Function to print the minimum index character 
// in a string.
class Main {
    static String printMinIndexChar(String str, 
                                    String patt) {
        // Creating a HashSet to store the presence of 
        // characters in patt.
        Set<Character> hash = new HashSet<>();
        
        // Iterating over each character in patt and 
        // updating its presence.
        for (char ch : patt.toCharArray()) 
            hash.add(ch);

        // Iterating over each character in str.
        for (char ch : str.toCharArray()) {
          
            // If current character in str is present
            // in the hash set, we have found the minimum
            // index character.
            if (hash.contains(ch)) {
              
                // Returning the minimum index character
                // as a string.
                return String.valueOf(ch);
            }
        }

        // If no minimum index character found
        return "$";
    }

    public static void main(String[] args) {
        String str = "geeksforgeeks"; 
        String patt = "set";
        String result = printMinIndexChar(str, patt);
        System.out.println(result); 
    }
}
Python
def minIndexChar(str, patt):
    # Dictionary to store the first index of each character in 'str'
    um = {}

    min_index = float('inf')

    m = len(str)
    n = len(patt)

    # Store the first index of each character of 'str'
    for i in range(m):
        if str[i] not in um:
            um[str[i]] = i

    # Traverse the string 'patt'
    for j in range(n):
        if patt[j] in um and um[patt[j]] < min_index:
            min_index = um[patt[j]]

    return min_index if min_index != float('inf') else -1

# Driver program to test above
if __name__ == "__main__":
    str1 = "geeksforgeeks"
    patt = "set"
    print(minIndexChar(str1, patt))  # Output: 1
C#
using System;
using System.Collections.Generic;

// Function to print the minimum index character 
// in a string.
class Program {
    static string printMinIndexChar(string str, 
                                    string patt) {
        // Creating a HashSet to store the presence of 
        // characters in patt.
        HashSet<char> hash = new HashSet<char>();
        
        // Iterating over each character in patt and 
        // updating its presence.
        foreach (char ch in patt)
            hash.Add(ch);

        // Iterating over each character in str.
        foreach (char ch in str) {
          
            // If current character in str is present
            // in the hash set, we have found the minimum
            // index character.
            if (hash.Contains(ch)) {
              
                // Returning the minimum index character
                // as a string.
                return ch.ToString();
            }
        }

        // If no minimum index character found
        return "$";
    }

    static void Main(string[] args) {
        string str = "geeksforgeeks"; 
        string patt = "set";
        string result = printMinIndexChar(str, patt);
        Console.WriteLine(result); 
    }
}
JavaScript
// Function to print the minimum index character 
// in a string.
function printMinIndexChar(str, patt) {
    // Creating a Set to store the presence of 
    // characters in patt.
    let hash = new Set();
    
    // Iterating over each character in patt and 
    // updating its presence.
    for (let ch of patt) 
        hash.add(ch);

    // Iterating over each character in str.
    for (let ch of str) {
      
        // If current character in str is present
        // in the hash set, we have found the minimum
        // index character.
        if (hash.has(ch)) {
          
            // Returning the minimum index character
            // as a string.
            return ch;
        }
    }

    // If no minimum index character found
    return "$";
}

let str = "geeksforgeeks"; 
let patt = "set";
let result = printMinIndexChar(str, patt);
console.log(result);

Output
e

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



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg
  翻译: