Minimum Window Substring
hardBlind 75NeetCode 150stringssliding-windowhashing
Problem
Given a string s and a pattern t, find the shortest contiguous substring of s that contains every character of t including duplicates. If none exists, return an empty string.
Examples
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
The shortest window covering A, B, and C.
Input: s = "a", t = "aa"
Output: ""
s lacks a second a.
Constraints
- • 1 <= s.length, t.length <= 10^5
- • Strings contain upper and lower case English letters
Hints(tap to reveal)
- 1. Track how many required characters are still missing.
- 2. Expand to satisfy, then contract to minimize.
Optimal approach(spoiler)
- Count the required character frequencies from t.
- Expand the right edge, decrementing needs and a missing counter.
- Once all needs are met, contract the left edge while still valid.
- Record the smallest valid window seen.
- O(n) time, O(alphabet) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor