← Questions
Minimum window substring containing every character of a pattern
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Given strings s and t, return the shortest substring of s that contains every character of t, with repeats counted. Return "" if there is none.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
min_window(s: str, t: str) -> str— if several windows are equally short, return the one that starts first. An emptytreturns"".
Example
min_window("ADOBECODEBANC", "ABC") -> "BANC"
min_window("a", "aa") -> "" # t needs two a's
min_window("aa", "aa") -> "aa"
Constraints
-
0 <= len(s), len(t) <= 10^5. Any characters, case-sensitive. - Aim for O(len(s) + len(t)) time.
Clarifying questions
- Do repeated characters in
thave to appear that many times? - Is the match case-sensitive?
- Which window wins a tie?
- Return the substring or its indices?
What a strong answer covers
- A sliding window with a
needcount fortand a counter of how many distinct characters are fully covered. - Grow the right end until the window covers
t. Then shrink from the left while it still covers, recording the best window, and stop when a needed character falls short. - O(len(s) + len(t)) time, O(alphabet) space, and why each pointer moves at most
len(s)times. - Tests:
tlonger thans,twith repeats, the answer at the very start or end, no answer.
Follow-ups
- The characters of
tmust appear in order (a subsequence), not just be present. - Many queries
tagainst the same longs. - Return every minimal window.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding


