← All problems

76. Minimum Window Substring

HardOpen on LeetCodeProblem statement

Problem Statement

76. Minimum Window Substring

Hard


Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".

The testcases will be generated such that the answer is unique.

A substring is a contiguous sequence of characters within the string.

 

Example 1:

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.

Example 2:

Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.

Example 3:

Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.

 

Constraints:

 

Follow up: Could you find an algorithm that runs in O(m + n) time?

C++ — alternative 1

Source file
class Solution {
public:
    string minWindow(string s, string t) {
        if(s.length()<t.length())
            return "";
        map<char, int> m;
        int minSum=INT_MAX;
        for(char c: t)
            m[c]++;
        int lt=0, rt=0, ct=0;
        string res = s;
        for(;rt<s.size();rt++){
            if(m[s[rt]]>0)
                ct++;
            m[s[rt]]--;
            if(ct==t.length()){
                while(m[s[lt]]<0 && lt<rt)   // rm elems from slidin win bcz -ve => we've more than reqd
                    m[s[lt]]++, lt++;
                if(res.length()>rt-lt+1)
                    res=s.substr(lt,rt-lt+1);
                // cout << res << "$" <<endl;
            }
            // cout << s.substr(lt, rt-lt+1) << "\t";
        }
        for(auto k:m)
            if(k.second>0)
                return "";
        return res;
    }
};