Find the minimum window substring.
MediumGiven two strings s and t, return the shortest substring of s that contains every character of t, including repeats. If no such substring exists, return an empty string.
The characters can appear in any order within the substring. The tests only use inputs where the shortest substring is unique.
Example 1
Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC"
BANC is the shortest substring that contains A, B and C.
Example 2
Input: s = "a", t = "aa" Output: ""
t needs two a characters, but s only has one.
Constraints
1 <= s.length, t.length <= 100000sandtcontain only uppercase and lowercase English letters.- Letters are case-sensitive, so
adoesn't matchA.
Approach
Checking every substring of s takes at least quadratic time. A sliding window does better because of one property: if a window contains all of t, so does every larger window around it. So for each right end, you only need the smallest window that ends there, and the left end of that window never moves backward.
Grow the window one character at a time from the right. As soon as it contains all of t, record it if it's the shortest so far, then move the left end forward until the window is missing something. Then grow it from the right again.
To check whether the window is valid in constant time, keep a count of how many more of each character the window needs, starting from the counts in t, plus a single missing total. Adding a character that's still needed lowers missing. Removing a character that the window then needs again raises it. The window covers t exactly when missing is 0.
Steps
- Count the characters of
tintoneed, and setmissingto the length oft. - Move
rightacrosss. Ifneedfor the new character is above0, lowermissing. Then lower that character's count, even if it goes negative. - While
missingis0, record the window if it's the shortest so far. Then raise the count of the character atleft, raisemissingif that count is now above0, and moveleftforward. - Return the shortest window you recorded, or an empty string if there wasn't one.
Complexity
- Time:
O(m + n), wheremandnare the lengths ofsandt. Each pointer moves acrosssat most once. - Space:
O(k), wherekis the number of distinct characters. With only English letters, that's constant.
Common mistakes
- Treating
tas a set of characters. Iftis"aa", the window needs twoacharacters, so track counts, not just presence. - Lowering
missingfor every character you add. Only characters the window still needs count, which is whyneedis checked before it's lowered. - Recording the window after shrinking it instead of before. The step that makes
missingpositive also makes the window invalid.
Lewin (Dropbox SWE) answers the minimum window substring interview question.
Interview experiences
1 sharedRelated questions
Find the minimum sum subarray of size k.Find the longest repeating substring.Find the maximum subarray sum.Related courses







