Skip to content

Commit 683fab4

Browse files
Create min_window_substring.cpp
1 parent 1cbb222 commit 683fab4

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

min_window_substring.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
public:
3+
string minWindow(string s, string t) {
4+
5+
if(s.size() < t.size()) return "";
6+
7+
int hashPattern[256] = {0}, hashString[256] = {0};
8+
for(auto ch : t) {
9+
hashPattern[ch]++;
10+
}
11+
12+
int count = 0, start = 0, startIndex = -1, minWindowLength = INT_MAX;
13+
for(int i=0; i<s.size(); i++) {
14+
15+
//increment occurence of char in string_map
16+
hashString[s[i]]++;
17+
18+
// Here we check if the current char is in the pattern as well.
19+
// Since we calculate running frequency of char in string_map as we encounter in the for loop, we do a <= comparison of hashString[s[i]] and hashPattern[s[i]]. It means the count of current char in string_map should be either equal count of current char in hash_map or less than count of current char in hash_map
20+
//if s[i] is in pattern_map and hashString[s[i]] == hashPattern[s[i]] or hashString[s[i]] < hashPattern[s[i]]
21+
if(hashPattern[s[i]] != 0 and hashString[s[i]] <= hashPattern[s[i]]) {
22+
count++;
23+
}
24+
25+
26+
if(count == t.size()) { //if we find the pattern in the string
27+
28+
//minimize the window from start
29+
30+
while((hashString[s[start]] > hashPattern[s[start]]) or hashPattern[s[start]] == 0) {
31+
32+
//if current char at start is occuring more times than in pattern, we can minimize the window.
33+
//remove the current char at start from string_map and increment start; thereby reducing size of window.
34+
if(hashString[s[start]] > hashPattern[s[start]]) hashString[s[start]]--;
35+
36+
//if the current char at start is not present in the pattern, just increment the start...
37+
start++;
38+
}
39+
40+
//get the minimum of all the windows seen so far
41+
int currentWindowLength = i - start + 1;
42+
if(currentWindowLength < minWindowLength) {
43+
minWindowLength = currentWindowLength;
44+
startIndex = start;
45+
}
46+
}
47+
}
48+
49+
if(startIndex == -1) return "";
50+
else return s.substr(startIndex, minWindowLength);
51+
52+
}
53+
};

0 commit comments

Comments
 (0)