Solve LeetCode 76: Minimum Window Substring in Python with a deficit-count window approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Hard |
|---|---|
| Topic | Sliding Window |
| Reusable pattern | deficit-count window |
| Complexity | O(n) time and O(k) space |
What the problem is testing
Expand while satisfying required character counts, then shrink while the window remains valid to minimize it.
Algorithm
- Expand while satisfying required character counts, then shrink while the window remains valid to minimize it.
- Maintain this invariant: formed counts how many required character classes currently meet their exact demand.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
class Solution:
def minWindow(self, s, t):
if not t: return ""
need, have = Counter(t), defaultdict(int)
required, formed, left = len(need), 0, 0
best = (float("inf"), 0, 0)
for right, char in enumerate(s):
have[char] += 1
if char in need and have[char] == need[char]: formed += 1
while formed == required:
if right - left + 1 < best[0]: best = (right - left + 1, left, right)
old = s[left]; have[old] -= 1; left += 1
if old in need and have[old] < need[old]: formed -= 1
return "" if best[0] == float("inf") else s[best[1]:best[2] + 1]Why this is correct
The proof follows the maintained state: formed counts how many required character classes currently meet their exact demand. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(n) time and O(k) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
Repeated required characters matter; return an empty string if no valid window exists.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 30. Substring with Concatenation of All Words · Next: 36. Valid Sudoku