Blind 75 · Sliding Window

Minimum Window Substring

Hard

Watch the walkthrough (6:24)

Problem

The input is two strings, s and t.
Find the shortest substring of s that holds every letter of t, repeats included.
If no substring does, return the empty string.
When there is an answer, there is only one.

Examples

Example 1:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"

Example 2:
Input: s = "a", t = "a"
Output: "a"

Example 3:
Input: s = "a", t = "aa"
Output: ""
Explanation: one a cannot cover two.

Example 4:
Input: s = "ab", t = "b"
Output: "b"

Constraints

1 <= s.length, t.length <= 10^5
s and t consist of English letters.

Prerequisites

Sliding windows — a left and right edge moving forward only, and the invariant that decides when the left edge advances.
Hash maps or fixed-size counts for what the window currently holds.

How to think about it

1. Grow to Cover, Shrink to Minimise Optimal

Intuition

Grow until nothing is missing, then shrink while nothing is missing. Two motions, not one: extend the right edge until the window covers everything t needs, then pull the left edge in as far as coverage survives, recording the smallest window each time it does. Coverage is tracked as a single integer of outstanding requirements rather than by comparing maps — that counter keeps each step to one check instead of a pass over the alphabet.

Algorithm

1. Count what t requires. Set an outstanding counter to t's length.
2. Extend right: if the character was still required, decrement the counter.
3. While the counter is zero, the window covers t — record it if smallest, then release the left character; if that makes it required again, raise the counter.
4. Return the smallest window recorded, or the empty string.

Time & Space

Time O(s + t) — each edge crosses the string once. Space O(1) over a fixed character set.