Skip to content

Commit e95711a

Browse files
committed
Smallest window in a string containing all the characters of another string
1 parent 082078b commit e95711a

File tree

2 files changed

+71
-1
lines changed

2 files changed

+71
-1
lines changed

Some_More_Strings/README.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,11 @@
2828
Output:
2929
It sa longdy ear.
3030
Geks fore
31-
Explanation:For the 1st test case. Print first "I" and then ignore next "i". Similarly print first space then ignore next space. and so on.
31+
Explanation:For the 1st test case. Print first "I" and then ignore next "i". Similarly print first space then ignore next space. and so on.
32+
33+
## 4. Smallest window in a string containing all the characters of another string:
34+
Given two strings S and P. Find the smallest window in the string S consisting of all the characters(including duplicates) of the string P. Return "-1" in case there is no such window present. In case there are multiple such windows of same length, return the one with the least starting index.
35+
Example 1:
36+
Input: S = "timetopractice", P = "toc"
37+
Output: toprac
38+
Explanation: "toprac" is the smallest substring in which "toc" can be found.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// { Driver Code Starts
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
6+
// } Driver Code Ends
7+
class Solution
8+
{
9+
public:
10+
//Function to find the smallest window in the string s consisting
11+
//of all the characters of string p.
12+
string smallestWindow (string s, string p)
13+
{
14+
// Your code here
15+
int map[256] = {0};
16+
int count = 0;
17+
for(int i = 0 ; i < p.length() ; i++)
18+
{
19+
if(map[p[i]] == 0)
20+
count++;
21+
map[p[i]]++;
22+
}
23+
int res = INT_MAX, ind = 0, i = 0, j = 0;
24+
while(j < s.length())
25+
{
26+
map[s[j]]--;
27+
if(map[s[j]] == 0)
28+
count--;
29+
while(count == 0)
30+
{
31+
if(res > j - i + 1)
32+
{
33+
res = min(res, j - i + 1);
34+
ind = i;
35+
}
36+
map[s[i]]++;
37+
if(map[s[i]] > 0)
38+
count++;
39+
i++;
40+
}
41+
j++;
42+
}
43+
return res == INT_MAX ? "-1" : s.substr(ind, res);
44+
}
45+
};
46+
47+
// { Driver Code Starts.
48+
int main()
49+
{
50+
int t;
51+
cin>>t;
52+
while(t--)
53+
{
54+
string s;
55+
cin>>s;
56+
string pat;
57+
cin>>pat;
58+
Solution obj;
59+
cout<<obj.smallestWindow(s, pat)<<endl;
60+
61+
}
62+
return 0;
63+
} // } Driver Code Ends

0 commit comments

Comments
 (0)