-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Minimum_indexed_character.cpp
85 lines (75 loc) · 1.84 KB
/
Minimum_indexed_character.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
Description :
Given a string str and another string pattern. Find the character in pattern that
is present at the minimum index in str. If no character of patt is present in
str then print ‘No character found from the given pattern’.
*/
#include <bits/stdc++.h>
using namespace std;
class Pattern
{
public:
//Function to find the minimum indexed character.
int min_index(string str, string patt)
{
int minIndex = INT_MAX;
unordered_map<char, int> umap;
int n = patt.size();
int m = str.size();
//storing index character
for (int i = 0; i < m; i++)
if (umap.find(str[i]) == umap.end())
umap[str[i]] = i;
//iterating over the second string "patt".
for (int i = 0; i < n; i++)
{
if (umap.find(patt[i]) != umap.end() && umap[patt[i]] < minIndex)
{
//updating minimum index.
minIndex = umap[patt[i]];
}
}
if (minIndex != INT_MAX)
return minIndex;
else
return -1;
}
};
int main()
{
//input string
string str;
cout << "Enter the string " << endl;
cin >> str;
//pattern string
string pattern;
cout << "Enter the pattern to be found " << endl;
cin >> pattern;
Pattern ob;
int res = ob.min_index(str, pattern);
//if no pattern returned from the function
if (res == -1)
{
cout << "No character found from the given pattern " << endl;
}
else
{
cout << "First character present from pattern " << endl;
cout << str[res];
}
return 0;
}
/*
Time complexity : O(n)
Space complexity : O(n)
*/
/*
Test Case :
Input :
Enter the string
xyxyxz
Enter the pattern to be found
tree
Output :
No character found from the given pattern
*/