Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Find one extra character in a string
Next article icon

Find Minimum Indexed Character in String

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

Table of Content

  • [Naive Approach] Using Two Nested Loops – O(m*n) Time and O(1) Space
  • [Expected Approach] Using Frequency Array – O(n) Time and O(1) Space
  • [Other Approach] Using Set or Hashing – O(n) Time and O(1) space

[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
Find one extra character in a string
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Hash
  • Strings
  • Ola Cabs
  • STL
Practice Tags :
  • Ola Cabs
  • Hash
  • STL
  • Strings

Similar Reads

  • Find last index of a character in a string
    Given a string str and a character x, find last index of x in str. Examples : Input : str = "geeks", x = 'e' Output : 2 Last index of 'e' in "geeks" is: 2 Input : str = "Hello world!", x = 'o' Output : 7 Last index of 'o' is: 7 Recommended PracticeLast index of a character in the stringTry It! Metho
    8 min read
  • Find one extra character in a string
    Given two strings which are of lengths n and n+1. The second string contains all the characters of the first string, but there is one extra character. Your task is to find the extra character in the second string. Examples: Input : string strA = "abcd"; string strB = "cbdae"; Output : e string B con
    15+ min read
  • Find maximum occurring character in a string
    Given string str. The task is to find the maximum occurring character in the string str. Examples: Input: geeksforgeeksOutput: eExplanation: 'e' occurs 4 times in the string Input: testOutput: tExplanation: 't' occurs 2 times in the string Return the maximum occurring character in an input string us
    9 min read
  • Remove odd indexed characters from a given string
    Given string str of size N, the task is to remove the characters present at odd indices (0-based indexing) of a given string. Examples : Input: str = “abcdef”Output: aceExplanation:The characters 'b', 'd' and 'f' are present at odd indices, i.e. 1, 3 and 5 respectively. Therefore, they are removed f
    4 min read
  • Find repeated character present first in a string
    Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) Examples: Input : geeksforgeeks Output : g (mind that it will be g, not e.) Asked in: Goldman Sachs internship Simple Solution using O(N^2) complexity: The solution is to loop thro
    15 min read
  • Find characters which when increased by K are present in String
    Given a string s of lowercase English alphabets and integer K. the task is to check if each character after increasing their ASCII by K is present in the string or not. Return only unique characters and the first index where they are present. Examples: Input: s = "dszepvaxuo", k = 3Output: {{1, 's'}
    8 min read
  • Accessing characters by index in a String
    Given two strings str1 and an index, the task is to access the character at this index. Examples: Input: str = "hello", index = 1Output: e Input: str = "GfG", index = 2Output: G Accessing characters by index in a string:Individual characters in a string can be accessed by specifying the string name
    2 min read
  • Index of character depending on frequency count in string
    Given a string str containing only lowercase characters, the task is to answer Q queries of the following type: 1 C X: Find the largest i such that str[0...i] has exactly X occurrence of the character C.2 C X: Find the smallest i such that str[0...i] has exactly X occurrence of the character C. Exam
    10 min read
  • Print the middle character of a string
    Given string str, the task is to print the middle character of a string. If the length of the string is even, then there would be two middle characters, we need to print the second middle character. Examples: Input: str = "Java"Output: vExplanation: The length of the given string is even. Therefore,
    3 min read
  • Find the Nth occurrence of a character in the given String
    Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences