> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Minimum Window Substring Python Solution

> Tested Python solution for LeetCode 76 with 11 pytest cases. Generate a practice environment with lcpy.

LeetCode 76, Hard. Topics: Hash Table, String, Sliding Window. [View on LeetCode](https://leetcode.com/problems/minimum-window-substring/description/).

Generate this problem as a practice environment: tested reference solution, 11 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 76   # by problem number
lcpy gen -s minimum_window_substring   # by problem name
```

## Problem

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.

### Examples

```
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
```

**Explanation:** The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.

```
Input: s = "a", t = "a"
Output: "a"
```

**Explanation:** The entire string s is the minimum window.

```
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 <= 10^5`
* `s` and `t` consist of uppercase and lowercase English letters.

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

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_window_substring/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_window_substring/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import Counter


class Solution:
    # Sliding Window
    # Time: O(m + n) where m = len(s), n = len(t)
    # Space: O(k) where k is unique chars in t
    def min_window(self, s: str, t: str) -> str:
        if not t or len(t) > len(s):
            return ""

        need = Counter(t)

        left = 0
        formed = 0
        required = len(need)
        window_counts: dict[str, int] = {}

        # Result: (window length, left, right)
        ans: tuple[float, int | None, int | None] = (float("inf"), None, None)

        for right in range(len(s)):
            char = s[right]
            window_counts[char] = window_counts.get(char, 0) + 1

            # Check if current char frequency matches desired frequency in t
            if char in need and window_counts[char] == need[char]:
                formed += 1

            # Contract window until it's no longer valid
            while left <= right and formed == required:
                char = s[left]

                # Update result if this window is smaller
                if right - left + 1 < ans[0]:
                    ans = (right - left + 1, left, right)

                # Remove from left
                window_counts[char] -= 1
                if char in need and window_counts[char] < need[char]:
                    formed -= 1

                left += 1

        if ans[0] == float("inf"):
            return ""
        assert ans[1] is not None and ans[2] is not None
        return s[ans[1] : ans[2] + 1]
```

## Complexity

| Time                                  | Space                             |
| ------------------------------------- | --------------------------------- |
| O(m + n) where m = len(s), n = len(t) | O(k) where k is unique chars in t |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
