InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Minimum Window Substring

hard Original ↗ 00:00

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).

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug