76. Minimum Window Substring

1. Description

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.

2. Example

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.

3. Constraints

  • m == s.length
  • n == t.length
  • 1 <= m, n <= 105
  • s and t consist of uppercase and lowercase English letters.

4. Follow up

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

5. Solutions

Hash Table && Sliding Window

Time complexity: O(mn)
Space complexity: O(1)

class Solution {
public:
    string minWindow(const string &s, const string &t) {
        unordered_map<char, int> letter_count;
        int diff_letter_count = 0;
        for (auto letter : t) {
            ++letter_count[letter];
            if (letter_count[letter] == 1) {
                ++diff_letter_count;
            }
        }

        string min_window;
        for (int left = 0, right = 0; right < s.size(); ++right) {
            if (letter_count.find(s[right]) != letter_count.end()) {
                --letter_count[s[right]];
                if (letter_count[s[right]] == 0) {
                    --diff_letter_count;
                }

                if (diff_letter_count == 0) {
                    while (diff_letter_count == 0) {
                        if (letter_count.find(s[left]) != letter_count.end()) {
                            ++letter_count[s[left]];
                            if (letter_count[s[left]] == 1) {
                                ++diff_letter_count;
                            }
                        }

                        ++left;
                    }

                    string window = s.substr(left - 1, right - left + 2);
                    if (min_window.empty() || window.size() < min_window.size()) {
                        min_window = window;
                    }
                }
            }
        }

        return min_window;
    }
};
comments powered by Disqus