Skip to content
Problem · Canonical Warm-Up
hardsliding-window · hash-map · need-counterTime · O(|s| + |t|)Space · O(|s| + |t|)

Minimum Window Substring

Problem statement

Statement

Given strings s and t, return the shortest substring of s that contains every character of t, counting duplicates. If no such substring exists, return the empty string. The characters may appear in any order and the window may contain extras.

Examples

s = "ADOBECODEBANC", t = "ABC"
-> "BANC"            ("ADOBEC" also covers ABC but is longer)

s = "a", t = "a"
-> "a"

s = "a", t = "aa"
-> ""                (s holds only one 'a'; duplicates in t are required)

s = "ab", t = "b"
-> "b"

Constraints

  • 1 <= len(s), len(t) <= 10^5
  • Both strings contain uppercase and lowercase English letters, and case is significant.
  • The answer is guaranteed unique when one exists.

What this problem is really testing

Two things that are easy separately and awkward together: running a window whose validity is defined by multiset containment, and checking that validity in constant time.

The window mechanics invert the usual longest-window problem. There you expand while valid and shrink when the invariant breaks. Here validity is monotone in the other direction: a longer window is more likely to be valid, not less. So you expand until valid, then shrink while still valid, recording the length at each step, and stop shrinking the moment validity is lost. The shape of the loop follows from which direction the predicate is monotone, and being able to derive that rather than recall it is what separates candidates who have understood the sliding window from those who have memorised two templates.

The second half is the real engineering. "Does the window contain all of t?" is a comparison between two frequency maps, which costs O(alphabet) if you ask it directly, and asking it on every pointer move degrades the whole algorithm. The fix is to maintain a single integer, the number of distinct characters currently satisfied, and update it only at the exact moments a character crosses its threshold. Turning an O(k) predicate into an O(1) counter by tracking transitions rather than states is a technique that reappears constantly, and this problem is where most people meet it first.

The subtlety in that counter is the word "exactly". A character's satisfaction flips when its window count reaches its required count, not when it exceeds it. If t needs two As and the window has five, that is still one satisfied character, not four. Incrementing on every occurrence is the classic bug here and it inflates the counter until every window looks valid.