AAlgoLoopSpaced repetition for LeetCode
HARDSliding WindowLeetCode ↗

Minimum Window Substring

The key idea

Grow a window with a right pointer until it covers every character of t (counting duplicates), then shrink from the left as far as possible while the window stays valid. A formed counter that matches required distinct needs tells you in O(1) whether the current window is valid, so the whole scan is linear.

Problem

Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".

The testcases are generated such that the answer is unique.

A substring is a contiguous sequence of characters within the string.

Constraints

Examples

Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC"
Input: s = "a", t = "a" Output: "a"
Input: s = "a", t = "aa" Output: ""

Complexity

Time: O(m + n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Sliding Window problems