76. Minimum Window Substring – Solution [Brute-Force to Best]

Here’s the question link on Leetcode 76. Minimum Window Substring:

https://leetcode.com/problems/minimum-window-substring/description

Brute Force – Check All Substrings

The simplest approach is to generate every possible substring of s and check whether it contains all the characters of t.

We can use a frequency array to track the characters in each substring.

class Solution {
public:
    string minWindow(string s, string t) {
        int n = s.size();
        int minLen = INT_MAX;
        string ans = "";

        vector<int> target(128, 0);

        for(char c : t) {
            target[c]++;
        }

        for(int i = 0; i < n; i++) {
            vector<int> freq(128, 0);

            for(int j = i; j < n; j++) {
                freq[s[j]]++;

                bool valid = true;

                for(int k = 0; k < 128; k++) {
                    if(freq[k] < target[k]) {
                        valid = false;
                        break;
                    }
                }

                if(valid && j - i + 1 < minLen) {
                    minLen = j - i + 1;
                    ans = s.substr(i, minLen);
                }
            }
        }

        return ans;
    }
};
76. Minimum Window Substring Brute Force Solution

Optimal – Sliding Window

Instead of checking every possible substring, we can use the sliding window technique.

We’ll maintain two pointers, left and right, and expand our window until it contains all the characters of t.

Once we have a valid window, we’ll try shrinking it from the left to find a smaller answer.

The trick is to maintain a variable missing, which tells us how many characters from t are still missing.

class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> freq(128, 0);

        for(char c : t) {
            freq[c]++;
        }

        int left = 0, missing = t.size();
        int minLen = INT_MAX, start = 0;

        for(int right = 0; right < s.size(); right++) {
            char c = s[right];

            if(freq[c] > 0) {
                missing--;
            }

            freq[c]--;

            while(missing == 0) {
                if(right - left + 1 < minLen) {
                    minLen = right - left + 1;
                    start = left;
                }

                char ch = s[left];
                freq[ch]++;

                if(freq[ch] > 0) {
                    missing++;
                }

                left++;
            }
        }

        return minLen == INT_MAX ? "" : s.substr(start, minLen);
    }
};
76. Minimum Window Substring Optimal Solution

Leave a Reply