> For the complete documentation index, see [llms.txt](https://nataliekung.gitbook.io/ladder_code/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nataliekung.gitbook.io/ladder_code/hua-dong-chuang-kou/minimum-window-substring.md).

# Minimum Window Substring

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

&#x20;

**Example 1:**

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

**Example 2:**

<pre><code><strong>Input: s = "a", t = "a"
</strong><strong>Output: "a"
</strong><strong>Explanation: The entire string s is the minimum window.
</strong></code></pre>

**Example 3:**

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

&#x20;

**Constraints:**

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

&#x20;

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

分析：

双指针+counter

注意required\_char=len(counter\_t) not len(t) 需要unique number of char

````
```python3
from collections import Counter


class Solution:
    def minWindow(self, s: str, t: str) -> str:
        if len(s) < len(t):
            return ""
        min_start,min_len,left = 0, float("inf"),0
        
        left = 0
        count_window = Counter()
        count_t = Counter(t)
        formed_char = 0
        required_char = len(count_t)
        for right, char in enumerate(s):
            count_window[char] += 1
            if count_window[char] == count_t[char]:
                formed_char += 1
            while formed_char == required_char:
                if min_len > right - left + 1:
                    min_len = right - left + 1
                    min_start = left
                
                if count_window[s[left]] == count_t[s[left]]:
                    formed_char -= 1 
                count_window[s[left]] -= 1
                left += 1
        return s[min_start: min_start + min_len] if min_len != float("inf") else ""
                






```
````
