Minimum Window Substring

hard

Given two strings s and t, return the shortest substring of s that contains every character of t, counting multiplicities (if t has two as, the window must too).

If no such window exists, return the empty string "". When several shortest windows exist, return the one that starts earliest.

Hints

Grow the window until it contains all of t, then try to shrink it from the left.
Track a 'need' count per character and a single 'missing' counter for how many are still unmet.
When missing hits zero the window is valid; record it as you shrink while it stays valid.

Common doubts

It counts how many required characters (with multiplicity) are still unmet. It drops when you consume a still-needed character and rises when shrinking would remove one — so validity is just 'missing == 0'.
Characters not in t, or extra copies beyond what t needs, don't reduce the requirement. Their need count is <= 0, so they leave missing unchanged.
Inside the shrink loop, while the window is valid — that's exactly when you have a covering window and are minimizing its length.

Interview follow-ups

Track how many times the minimum length is achieved during the shrink phase, resetting when a strictly smaller window appears.
Use a hash map instead of a fixed array for need/have; the algorithm is identical and stays O(n + m).

Fun facts

  • Minimum Window Substring is the canonical 'shortest window' problem — the mirror image of all the 'longest window' problems in this chapter.
  • The single 'missing' counter trick — collapsing a whole map comparison into one integer — recurs in anagram and permutation-in-string problems.

Asked at

AmazonGoogleMetaMicrosoftUber
Frequently Sometimes Occasionally
Example 1
Input: s = "ADOBECODEBANC", t = "ABC"
Output: BANC
The shortest window of s containing A, B, and C is "BANC".
Example 2
Input: s = "a", t = "aa"
Output: 
s has only one 'a' but t needs two, so no valid window exists.
Constraints

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

Solve this problem →