Given two strings s and t, return the minimum window substring of s such that every character in t (including duplicates) is included in the window.
Most tutorials use two hash maps (dict or unordered_map) to track character counts and compare all keys on every step. Under high-throughput streaming text, hash lookups and memory allocations kill CPU cache performance. How can we implement this with a single 128-element integer vector and a single integer variable missing_count?
Minimum Window Substring is the crown jewel of sliding window problems. The difference between a junior solution and a staff engineer solution comes down to how window validation is tracked.
1. The Trap: Comparing Two Hash Maps
In naive implementations, developers maintain two hash maps:
target_countsandwindow_counts. Whenever the window slides, they loop through the keys oftarget_countsto see if the window is valid. That turns an $O(N)$ algorithm into $O(N cdot |Sigma|)$ with heavy hash table overhead!2. The Staff Engineer Pattern: Single Vector + Deficit Counter
We can optimize this down to bare metal with two simple tricks:
required): We setrequired = len(t). When expanding the window with pointerr, ifcounts[s[r]] > 0, that character was actively needed, so we decrementrequired--. Whenrequired == 0, the window is 100% valid! We don’t have to check any other variables!Clean Python 3.12 Implementation
Complexity Breakdown
O(|s| + |t|). Therightpointer advances|s|times. Theleftpointer advances at most|s|times. Total pointer advances =2|s|.O(1)auxiliary space. Exactly 128 integers on the stack.