LeetCode 76: Minimum Window Substring is a Hard sliding window problem. This Python walkthrough develops a deficit-count window solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Hard |
|---|---|
| Topic | Sliding Window |
| Reusable pattern | deficit-count window |
| Complexity | O(n) time and O(k) space |
Recognizing the pattern
A sliding window fits when validity changes incrementally as the right edge expands and the left edge contracts.
For this problem specifically, expand while satisfying required character counts, then shrink while the window remains valid to minimize it. The invariant worth writing beside the code is: formed counts how many required character classes currently meet their exact demand.
Step-by-step algorithm
- Identify the input state consumed by
minWindow(s, t)and initialize the data required by the deficit-count window pattern. - Expand while satisfying required character counts, then shrink while the window remains valid to minimize it.
- After each update, verify the page’s central invariant: formed counts how many required character classes currently meet their exact demand.
- Finish only after the boundary behavior is covered: Repeated required characters matter; return an empty string if no valid window exists.
Python solution
from collections import Counter, defaultdict
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]Reading the implementation
The main entry point is minWindow(s, t). The named working state includes need, required, best, old; those variables make the deficit-count window state visible instead of hiding it in incidental control flow.
The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, expand while satisfying required character counts, then shrink while the window remains valid to minimize it.
Correctness argument
Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.
Preservation. Expand while satisfying required character counts, then shrink while the window remains valid to minimize it. The chosen movement discards only candidates that cannot improve the answer; afterward, formed counts how many required character classes currently meet their exact demand.
Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.
Complexity and trade-offs
O(n) time and O(k) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Enumerating every substring or subarray is conceptually simple but recomputes almost the same state for overlapping ranges. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().minWindow("ADOBECODEBANC","ABC") == "BANC"Common mistakes and edge cases
- Problem-specific boundary: Repeated required characters matter; return an empty string if no valid window exists.
- Pattern-level pitfall: Update counts in the correct order when an item enters or leaves, especially when duplicate requirements are present.
- Invariant check: after every update, confirm that formed counts how many required character classes currently meet their exact demand.
Interview review checklist
- Explain why deficit-count window matches the structure of this input.
- State the invariant in one sentence before tracing code: formed counts how many required character classes currently meet their exact demand.
- Derive O(n) time and O(k) space from how many times each element or state is visited.
- Test the boundary explicitly: Repeated required characters matter; return an empty string if no valid window exists.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 30. Substring with Concatenation of All Words · Next: 36. Valid Sudoku