Minimum Window Substring solution explained
Minimum Window Substring is solved with a sliding window: move a right edge forward until the window holds every required character with its multiplicity, then move the left edge forward while it still does, recording the shortest window seen. A count table of what is still owed plus one counter of missing characters makes each check O(1), so the whole scan runs in O(|s| + |t|) time.
By Evin JohnPublished 9 min read
The problem, in our words
You get a longer string, call it the text, and a shorter one, the pattern. Find the shortest contiguous piece of the text that contains every character of the pattern at least as many times as the pattern does. Other characters may sit inside the piece too. Return the piece itself, or an empty string if the text cannot cover the pattern at all. Most versions promise a single shortest answer; if several tie, the code below returns the leftmost one.
| Text | Pattern | Shortest covering window | Why |
|---|---|---|---|
plantonapeak | ant | ant | The letters appear together near the start |
dbcaxcbad | abc | bca | Two windows of length 3 exist; the leftmost is returned |
bbxaxba | abb | bbxa | Two b's are required, so axb is not enough |
weekend | eek | eek | Repeated e's must be matched twice |
xyz | xx | empty | The text has only one x |
aa | aa | aa | The whole text is the answer |
Ask early: is matching case-sensitive (usually yes, so A and a differ), what should an empty pattern return (the empty string is the common convention), and is the answer the substring or its start and length. Also confirm that repeats in the pattern must be matched, since that changes the solution.
What this round is checking
This is a harder sliding-window question, often used once a candidate has handled a simpler window problem. It tests three things together: whether you see that the window should grow and shrink rather than stay fixed, whether you can keep the validity check cheap instead of comparing two count tables at every step, and whether your bookkeeping survives repeated characters. Many failed attempts are correct in idea and lose time on off-by-one errors when recording the best window, so a clean, testable structure matters as much as the idea.
Slow but sure: try every start
For each starting position, extend the end one character at a time while counting what the window holds, and stop as soon as it covers the pattern, because any longer window from that start can only be worse. Comparing the counts costs O(σ) for σ distinct pattern characters, so the worst case is O(n² · σ) time for a text of length n. It is easy to get right, which makes it a good reference to test the fast version against.
from collections import Counter
def covers(have, need):
return all(have[ch] >= count for ch, count in need.items())
def shortest_cover_brute(text, pattern):
if not pattern:
return ""
need = Counter(pattern)
best = ""
for start in range(len(text)):
have = Counter()
for end in range(start, len(text)):
have[text[end]] += 1
if covers(have, need):
if not best or end - start + 1 < len(best):
best = text[start:end + 1]
break # a longer window from this start cannot be shorter
return bestThe window that grows and shrinks
Notice two facts. If a window covers the pattern, any window that contains it also covers it. And if a window does not cover the pattern, any window inside it does not either. So for each right edge, the best left edge only ever moves forward. That gives two indexes that both move left to right, never backward, which is the signature of a sliding window.
For the bookkeeping, keep need, a table that starts as the pattern's counts and goes down as characters enter the window, plus missing, the number of pattern characters, repeats included, that the window still lacks. When a character enters and its entry in need was positive, it fills a real gap, so missing drops by one. Its entry drops either way; a negative entry just means the window has a spare copy. When a character leaves, its entry goes up, and if it becomes positive the window now lacks that character, so missing rises. The window covers the pattern exactly when missing is zero, which is an O(1) check.
- ExpandMove the right edge one character forward and update
needandmissingfor the character that came in. - While the window covers the pattern, record itIf it is shorter than the best so far, store its start and length. Store indexes, not slices, so recording costs O(1).
- ShrinkRemove the leftmost character, update its count, and raise
missingif that removal opened a gap. Move the left edge forward and check again. - FinishWhen the right edge reaches the end, return the stored window, or the empty string if nothing was ever recorded.
from collections import Counter
def shortest_cover(text, pattern):
if not pattern or len(pattern) > len(text):
return ""
need = Counter(pattern)
missing = len(pattern) # characters still owed, counting repeats
best_start, best_len = 0, float("inf")
left = 0
for right, ch in enumerate(text):
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0:
if right - left + 1 < best_len:
best_start, best_len = left, right - left + 1
gone = text[left]
need[gone] += 1
if need[gone] > 0:
missing += 1
left += 1
return "" if best_len == float("inf") else text[best_start:best_start + best_len]function shortestCover(text, pattern) {
if (pattern.length === 0 || pattern.length > text.length) return "";
const need = new Map();
for (const ch of pattern) need.set(ch, (need.get(ch) || 0) + 1);
let missing = pattern.length;
let bestStart = 0;
let bestLen = Infinity;
let left = 0;
for (let right = 0; right < text.length; right++) {
const ch = text[right];
const owed = need.get(ch) || 0;
if (owed > 0) missing -= 1;
need.set(ch, owed - 1);
while (missing === 0) {
if (right - left + 1 < bestLen) {
bestStart = left;
bestLen = right - left + 1;
}
const gone = text[left];
need.set(gone, need.get(gone) + 1);
if (need.get(gone) > 0) missing += 1;
left += 1;
}
}
return bestLen === Infinity ? "" : text.slice(bestStart, bestStart + bestLen);
}Characters that are not in the pattern also get entries in the table, and they go negative while inside the window. That is fine: they never become positive, so they never touch missing. In the JavaScript version, need.get(gone) is always defined when shrinking, because every character the left edge passes was added by the right edge earlier. The JavaScript loop indexes UTF-16 code units, which is the right unit for the usual ASCII version of the question; with emoji or other characters outside the basic plane, ask how a character is defined.
A trace you can check by hand
| Right edge reaches | Covering windows checked | Best so far |
|---|---|---|
| index 0 to 2 (d, b, c) | none, a is still missing | none |
| index 3 (a) | dbca, then bca | bca |
| index 4 and 5 (x, c) | none, b left the window | bca |
| index 6 (b) | caxcb, then axcb | bca |
| index 7 (a) | xcba, then cba | bca, since cba ties and does not beat it |
| index 8 (d) | none, c left the window | bca |
Cost of each approach
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Every start, extend until covered | O(n² · σ) worst case | O(σ) | Reference and opening answer |
| Window, compare full tables each step | O(n · σ) | O(σ) | Correct, but the check is not O(1) |
| Window with a missing counter | O(n + m) | O(σ) | The expected answer |
| Same, after filtering the text to pattern characters | O(n + m) | O(n) | Faster when most of the text is irrelevant |
Each index enters the window once on the right and leaves at most once on the left, so the two loops together do at most 2n steps on top of the O(m) to build the table.
Edge cases
- Empty pattern: return the empty string, by convention. Confirm it.
- Pattern longer than the text: no window can cover it, so return empty right away.
- Pattern characters missing from the text entirely, or present too few times, like
xyzwithxx. - Repeated pattern characters, like
abb, where one b is not enough. - The answer is the whole text, or a single character when the pattern has length one.
- Upper and lower case, if the interviewer says they should match. Fold both strings first.
Bugs that show up under pressure
- Tracking only which characters are present, not how many, so
bbxaxbawithabbreturns a window with a single b. - Comparing the whole window table with the pattern table on every step, which works but hides the O(1) check the interviewer hoped to see.
- Recording the best window after shrinking instead of before, which records a window that no longer covers the pattern.
- Slicing the substring every time a better window is found, adding O(n) per update. Keep the start and length, slice once at the end.
- Returning
Noneornullinstead of the agreed empty string when there is no answer.
How to explain it out loud
Fictional example
- Candidate
- If a window covers the pattern, so does every bigger window around it. So for each right edge I only ever need to move the left edge forward, which means a sliding window with two forward-only indexes.
- Candidate
- I keep a table of how many of each pattern character I still owe and a single number for the total still missing. A character coming in reduces missing only if I still owed it; one going out increases missing only if it opens a gap.
- Interviewer
- And when do you record the answer?
- Candidate
- Every time missing is zero, before I shrink. I store the start and length and slice once at the end. Each index enters and leaves at most once, so it is linear in the two string lengths.
Follow-ups
- Order matters: the pattern must appear as a subsequence, not just as a multiset. That is a different problem; a forward scan to find a match then a backward scan to tighten it, or dynamic programming, replaces the counts.
- Find every place where a rearrangement of the pattern appears. The window becomes fixed at the pattern length, and the same count table tells you when it matches exactly.
- The longest window with at most k distinct characters. Same grow-and-shrink frame, with the rule flipped: shrink while the window breaks the limit, record after it is valid again.
- Very long text with a tiny pattern. Filter the text to positions holding pattern characters first, then run the window over that shorter list.
Related walkthroughs
The counting idea comes straight from Valid Anagram, where one table balances two strings. Sliding Window Maximum keeps the window size fixed and needs a deque to answer its question, and Longest Substring Without Repeating Characters is the gentler variable-window problem to try first. Group Anagrams turns the same count table into a dictionary key. All of them are sorted by pattern on the coding problems hub.
Working on window problems with Natively
Window problems are mostly lost in the bookkeeping, so it helps to review exactly what you said while setting up the counters. Natively runs on Mac and Windows and transcribes your mock session, letting you look back at whether you named the missing counter before coding or improvised it halfway through. During practice it can also read a problem statement from a screenshot and offer a starting approach. The AI assistant for coding interviews covers how that works.
Questions people ask
How do you solve Minimum Window Substring?
Use a sliding window. Move the right edge until the window contains every pattern character with its count, then move the left edge while it still does, recording the shortest window. A count table and a missing counter keep each step O(1).
What is the time complexity of Minimum Window Substring?
O(|s| + |t|): building the pattern table is O(|t|), and each index of the text enters and leaves the window at most once. Extra space is bounded by the number of distinct characters.
How do duplicate characters in the pattern work?
They must be matched as many times as they appear. Counting what is still owed per character, rather than which characters are present, handles this automatically.
What should be returned if no window exists?
Usually the empty string. Ask the interviewer, and return early when the pattern is longer than the text.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
