InterviewPrepKit

Home / Coding / Sliding Window

Minimum Window Substring

hard Original β†—
Solving tips
  • Recognize a variable-size (expand/contract) window with multiplicity: match a Counter of t, expand right until valid, then shrink left while still valid recording the min.
  • Keep an integer 'have' = number of distinct required chars whose count is fully met; the window is valid when have == number of distinct chars in t, keeping each check O(1).
  • Target O(|s|+|t|) time and O(alphabet) space; never compare whole Counters every step (reintroduces the alphabet factor).
  • Common pitfall: record best_left/best_len at the moment you find a shorter valid window, and only bump 'have' on the exact transition window[c]==need[c].

Problem

Given two strings s and t, find the shortest contiguous substring of s that contains every character of t, respecting multiplicity (if t has two 'a's, the window must contain at least two 'a's). Return that substring; if no window of s covers all of t, return the empty string "". The test data guarantees the answer is unique when it exists.

Examples

  • s = "ADOBECODEBANC", t = "ABC" β†’ "BANC" β€” the windows containing {A, B, C} include "ADOBEC" (length 6) and "BANC" (length 4); the shortest is "BANC".
  • s = "a", t = "a" β†’ "a" β€” the whole string is the (only) valid window.
  • s = "a", t = "aa" β†’ "" β€” t needs two 'a's but s only has one, so no window is valid.

Constraints

  • 1 <= len(s), len(t) <= 10^5
  • s and t consist of uppercase and lowercase English letters.
  • The 10^5 bound demands an O(n)-ish algorithm β€” anything that re-examines O(n) windows at O(n) cost each is too slow.

Think about it first

Hint 1 A window is "valid" when, for every character `c` in `t`, the window's count of `c` is at least `t`'s count of `c`. Track counts with a hash map β€” you never need to compare actual substrings.
Hint 2 If a window is valid, every larger window containing it is also valid β€” so once valid, growing the right end is pointless. Conversely, if it's invalid, shrinking it can't help. That monotonicity is what makes two pointers work.
Hint 3 Expand `right` until the window becomes valid; then advance `left` as far as possible while it stays valid, recording the best length; the moment it turns invalid, go back to expanding `right`. Keep an integer "how many required characters are fully satisfied" so each validity check is O(1).
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.