Skip to content

76. Minimum Window Substring

Hash Table String Sliding Window

Problem - 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.

 

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:

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

 

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

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def minWindow(self, s: str, t: str) -> str:
        find = Counter(t)
        window = Counter()
        left = count = 0
        start, min_num = -1, inf

        for right, char in enumerate(s):
            window[char] += 1
            if find[char] >= window[char]:
                count += 1
            while count == len(t):
                if right - left + 1 < min_num:
                    min_num = right - left + 1
                    start = left
                if find[s[left]] >= window[s[left]]:
                    count -= 1
                window[s[left]] -= 1
                left += 1

        return "" if start < 0 else s[start:start + min_num]

Submission Stats:

  • Runtime: 89 ms (44.17%)
  • Memory: 18 MB (93.19%)