76. Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example, S="ADOBECODEBANC" T="ABC" Minimum window is"BANC".

Note: If there is no such window in S that covers all characters in T, return the empty string"".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

Thoughts:

  1. "Do" Section keeps tracking "head" and "len" variable by "len"'s value

  2. Count: # character current sliding window needs (does not have)

class Solution {

public:
    string minWindow(string s, string t) {
        if(t.length() > s.length()) return "";
        unordered_map <char, int> map;
        for(int i = 0; i < t.length(); i++ ){
            ++map[t[i]];
        }

        int left = 0, right = 0, head = INT_MAX, len = INT_MAX, count = map.size();

        while(right < s.length()){
            char rightChar = s[right];
            if(map.find(rightChar) != map.end()){
                if(--map[rightChar] == 0) count --;
            }
            right ++;
            while(count == 0){  // here we already find the window that contains the targeted substring
                // do 
               if(right - left < len){
                    head = left;
                    len = right - left;
                }

                // increment
                char leftChar = s[left];
                if (map.find(leftChar)!= map.end()){
                    if(++map[leftChar] > 0){
                        count++;
                    }
                }       
                left ++;
            }
        }

        if(len == INT_MAX) return "";
        return s.substr(head, len);
    }
};

Template: https://leetcode.com/problems/minimum-window-substring/discuss/26808/Here-is-a-10-line-template-that-can-solve-most-'substring'-problems

Java Implementation: T: O(|S|), S:O(1)

Python: https://leetcode.com/problems/minimum-window-substring/discuss/26804/12-lines-Python

Java: https://leetcode.com/problems/minimum-window-substring/discuss/26805/Accepted-O(n)-solution

Last updated

Was this helpful?