← Back to LeetCode Notes

76. Minimum Window Substring

hard · hash-table · string · sliding-window · solved 2026.08.26 · 39 sec read

View on LeetCode ↗
C++
class Solution {public:    string minWindow(string s, string t) {        unordered_map<char, int> needCount;        unordered_map<char, int> haveCount;        int have = 0;        for (char a : t) {            needCount[a]++;        }        int need = needCount.size();        int l = 0;        int bestLen = INT_MAX, bestL = 0;        for (int r = 0; r < s.size(); r++) {            char c = s[r];            haveCount[c]++;            if (needCount.count(c) && haveCount[c] == needCount[c]) {                have++;            }            while (have == need) {                if (r - l + 1 < bestLen) {                    bestLen = r - l + 1;                    bestL = l;                }                haveCount[s[l]]--;                if (needCount.count(s[l]) &&                    haveCount[s[l]] < needCount[s[l]]) {                    have--;                }                l++;            }        }        return bestLen == INT_MAX ? "" : s.substr(bestL, bestLen);    }};

opkay great, this took me an hour and 30 minutes over i guess 4 days. uh i was just busy with work, moving in and and that kinda work, picking up leetcode again before interviews works and stuff. yeah i guess this was not that bad

i get how this works now for sliding window. first initlize your variables like l and r if you want to do while look for take care of r. in each interaiton, you gotta increase r, add that to the window by value as well. and if there is some condition then allow it and then try decreasting the window from the left to either keep some condition to restore the contidtion but find better condition, anything else before I wrap up this leetcode topic