Minimum Window Substring

50 min · minWindow()

A search result can contain every word you asked for and still be frustratingly broad. Your job here is to keep trimming until one more cut would lose something essential.

Given strings s and t, return the shortest substring — one unbroken slice of s — that contains every character required by t.

A few ground rules:

  • Character counts matter. Multiplicity means how many copies of a character are required: if t contains two As, the chosen slice needs two As too.
  • Uppercase and lowercase characters are different.
  • If no slice can satisfy t, return the empty string "".
  • Whenever an answer exists in these tests, its shortest valid slice is unique.

Constraints

  • 1 <= s.length <= 100_000
  • 1 <= t.length <= 100_000
  • s and t contain only lowercase and uppercase English letters.

Hints

Prove the direct version first

Choose each possible starting position, extend right, and stop when the current slice has every required count. Keep the shortest result you find.

Separate valid from minimal

Moving the right edge can make a slice valid. Once it is valid, moving the left edge asks a different question: how much can you discard before it becomes invalid?

Count satisfied character kinds

Store the required count for each character. A character kind becomes satisfied exactly when its window count reaches that requirement, and unsatisfied when its count drops below it.

Follow-up

Could you process s as a stream while keeping only the characters that still belong to the current candidate window?

Visible cases

Examples

Example 1

ready
Input
s = "ADOBECODEBANC"
t = "ABC"
Expected
"BANC"
Why
the final four characters supply the unique shortest cover

Example 2

ready
Input
s = "teamwork"
t = "Z"
Expected
""
Why
s contains no uppercase Z, so no window can qualify

Example 3

ready
Input
s = "aBac"
t = "caBa"
Expected
"aBac"
Why
every character is needed, including both copies of a

Interview signal

Asked at

AmazonMetaGoogleUber
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite