Skip to content

Instantly share code, notes, and snippets.

@sourabh2k15
Last active March 20, 2022 16:27
Show Gist options
  • Save sourabh2k15/13bc8a626bb8e2487605b19bd7d29363 to your computer and use it in GitHub Desktop.
Save sourabh2k15/13bc8a626bb8e2487605b19bd7d29363 to your computer and use it in GitHub Desktop.
Leetcode 76. Minimum Window Substring
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> table;
// initialize frequency table for t
for(char c : t){
table[c]++;
}
// initialize sliding window
int begin = 0, end = 0;
int counter = table.size();
int len = INT_MAX;
string ans = "";
// start sliding window
while(end < s.length()){
char endchar = s[end];
// if current char found in table, decrement count
if(table.find(endchar) != table.end()){
table[endchar]--;
if(table[endchar] == 0) counter--;
}
end++;
// if counter == 0, means we found an answer, now try to trim that window by sliding begin to right.
while(counter == 0){
// store new answer if smaller than previously best
if(end-begin < len){
len = end - begin;
ans = s.substr(begin, end - begin);
}
// begin char could be in table or not,
// if not then good for us, it was a wasteful char and we shortened the previously found substring.
// if found in table increment count in table, as we are leaving it out of window and moving ahead,
// so it would no longer be a part of the substring marked by begin-end window
// table only has count of chars required to make the present substring a valid candidate
// if the count goes above zero means that the current window is missing one char to be an answer candidate
int startchar = s[begin];
if(table.count(startchar) == 1){
table[startchar]++;
if(table[startchar] > 0) counter++;
}
begin++;
}
}
return ans;
}
};
@mcassiano
Copy link

mcassiano commented Jan 27, 2018

In line 24 and 25: shouldn't pattern be table? Thanks for the post! :)

@NellMartinez
Copy link

Why line 45 has the character converted into ASCII? I'm trying to convert your program to python and I cannot make it run.

@bengongon97
Copy link

@NellMartinez there is something went wrong there. I adapted it to java and yet it does not seem to work. I may have misunderstood the logic too. I even scanned c++ docs to make sure I am getting it right but I used startchar as character and not ASCII because I think it is how is it supposed to be. I think something is really messed up there but I am not sure what exactly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment