Try it first — give it 40 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get two strings, s (length m) and t (length n). Find the shortest substring of s that contains every character of t, including duplicates. If t has two as, the window needs at least two as. Return that substring, or "" if none exists. The test data guarantees the answer is unique.
Upper- and lower-case letters are different characters. Lengths go up to 10⁵.
Example: s = "ADOBECODEBANC", t = "ABC" → "BANC". Other windows such as "ADOBEC" also contain A, B and C, but "BANC" is the shortest.
Start with brute force
Try every start i. Extend the end j one step at a time, keeping counts, and stop at the first j where the window covers t. That's the shortest window starting at i. Keep the best one overall.
That's O(m²) windows in the worst case, and each check over the alphabet costs extra. For m = 10⁵, that's 10¹⁰ steps. Too slow.
Building the intuition
This Hard is two Medium ideas stacked together: the variable-size sliding window from Longest Substring Without Repeating Characters, and frequency counting from Permutation in String. The new part is noticing which way the window should move.
Step 1: a monotone property. Suppose s[2..9] covers t. Then s[2..10], s[1..9] and any window that contains s[2..9] also cover t. Adding characters never breaks coverage. Removing characters can.
That's the signal for a sliding window. For a fixed right end, the valid left ends form a run 0, 1, …, L. You want the biggest L, because that gives the shortest window. And when the right end moves forward, the best L can only move forward too. So neither pointer ever needs to move backwards.
Step 2: what does each pointer do?
- Move
rightforward until the window coverst(grow). - Then move
leftforward while the window still coverst, recording the length each time (shrink). - The moment it stops covering
t, go back to growing.
Step 3: checking "covers t" in O(1). Comparing two count arrays costs O(alphabet) every step. Instead, keep:
need[c]: how many more copies ofcthe window owes. It starts as the count ofcint. It goes negative when the window has spares.missing: the total number of characters still owed. It starts atlen(t).
When c enters the window: if need[c] > 0, that copy was really needed, so missing -= 1. Either way, need[c] -= 1.
When c leaves: need[c] += 1, and if need[c] is now > 0, you just gave away a needed copy, so missing += 1.
The window covers t exactly when missing == 0.
The optimal approach
- Fill
needfromt(an array of 128 slots covers ASCII). Setmissing = len(t). - For each
rightfrom 0 tom − 1:- take
s[right]: ifneed[c] > 0, decrementmissing; then decrementneed[c]; - while
missing == 0: record the window if it's the shortest so far, then drops[left](increment itsneed, and incrementmissingif it went above 0), thenleft += 1.
- take
- Return the best window, or
""if none was ever recorded.
The subtle detail: why negative counts are fine. need['B'] = −1 means the window holds one spare B. When a B leaves, need goes back to 0. That's still not positive, so missing stays put, which is right: you only lost a spare. This is how duplicates in t work with no extra code.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = [0] * 128 # need[c] = copies of c the window still owes us (negative = spare)
for c in t:
need[ord(c)] += 1
missing = len(t) # characters of t not yet covered by the window
best_start, best_len = 0, float("inf")
left = 0
for right, c in enumerate(s):
# Grow: take s[right]. It only helps if the window still owed us one.
if need[ord(c)] > 0:
missing -= 1
need[ord(c)] -= 1
# Shrink: while the window is valid, record it and drop the left char.
while missing == 0:
if right - left + 1 < best_len:
best_start, best_len = left, right - left + 1
out = ord(s[left])
need[out] += 1
if need[out] > 0: # we just gave away a char we needed
missing += 1
left += 1
return "" if best_len == float("inf") else s[best_start:best_start + best_len]class Solution {
public:
string minWindow(string s, string t) {
int need[128] = {0}; // need[c] = copies of c the window still owes us (negative = spare)
for (char c : t) need[c]++;
int missing = t.size(); // characters of t not yet covered by the window
int bestStart = 0, bestLen = INT_MAX;
int left = 0;
for (int right = 0; right < (int)s.size(); right++) {
// Grow: take s[right]. It only helps if the window still owed us one.
if (need[s[right]] > 0) missing--;
need[s[right]]--;
// Shrink: while the window is valid, record it and drop the left char.
while (missing == 0) {
if (right - left + 1 < bestLen) {
bestStart = left;
bestLen = right - left + 1;
}
need[s[left]]++;
if (need[s[left]] > 0) missing++; // we just gave away a char we needed
left++;
}
}
return bestLen == INT_MAX ? "" : s.substr(bestStart, bestLen);
}
};class Solution {
public String minWindow(String s, String t) {
int[] need = new int[128]; // need[c] = copies of c the window still owes us (negative = spare)
for (char c : t.toCharArray()) need[c]++;
int missing = t.length(); // characters of t not yet covered by the window
int bestStart = 0, bestLen = Integer.MAX_VALUE;
int left = 0;
for (int right = 0; right < s.length(); right++) {
// Grow: take s[right]. It only helps if the window still owed us one.
char c = s.charAt(right);
if (need[c] > 0) missing--;
need[c]--;
// Shrink: while the window is valid, record it and drop the left char.
while (missing == 0) {
if (right - left + 1 < bestLen) {
bestStart = left;
bestLen = right - left + 1;
}
char out = s.charAt(left);
need[out]++;
if (need[out] > 0) missing++; // we just gave away a char we needed
left++;
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + bestLen);
}
}/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function (s, t) {
const need = new Array(128).fill(0); // need[c] = copies of c the window still owes us (negative = spare)
for (const c of t) need[c.charCodeAt(0)]++;
let missing = t.length; // characters of t not yet covered by the window
let bestStart = 0, bestLen = Infinity;
let left = 0;
for (let right = 0; right < s.length; right++) {
// Grow: take s[right]. It only helps if the window still owed us one.
const c = s.charCodeAt(right);
if (need[c] > 0) missing--;
need[c]--;
// Shrink: while the window is valid, record it and drop the left char.
while (missing === 0) {
if (right - left + 1 < bestLen) {
bestStart = left;
bestLen = right - left + 1;
}
const out = s.charCodeAt(left);
need[out]++;
if (need[out] > 0) missing++; // we just gave away a char we needed
left++;
}
}
return bestLen === Infinity ? "" : s.slice(bestStart, bestStart + bestLen);
};Dry run
s = "ADOBECODEBANC", t = "ABC". Only the moments where something interesting happens are shown.
| right | char | missing after | Shrinking | Best so far |
|---|---|---|---|---|
| 0 | A | 2 | — | — |
| 3 | B | 1 | — | — |
| 5 | C | 0 | record [0, 5] "ADOBEC" (6). Drop A → missing 1, left = 1 | ADOBEC |
| 9 | B | 1 | spare B: need[B] = −1, missing unchanged | ADOBEC |
| 10 | A | 0 | [1, 10] (10) is no better. Drop D, O, B (spare), E. At [5, 10] the length is 6, which doesn't beat 6. Drop C → missing 1, left = 6 | ADOBEC |
| 12 | C | 0 | Drop O, D, E: [9, 12] "BANC" (4) is the new best. Drop B → missing 1, left = 10 | BANC |
Each character entered the window once and left at most once.
Complexity
- Time: O(m + n). Building
needreadstonce. Thenrightmovesmtimes andleftmoves at mostmtimes in total, across all iterations. The innerwhileis not a nested loop in cost terms. - Space: O(1). The
needarray has a fixed 128 slots, whatever the input size. (With a hash map it's O(k) for k distinct characters.)
Edge cases and traps
tlonger thans, or a character missing froms.missingnever reaches 0, so nothing is recorded. Return"".- Duplicates in
t, likes = "a",t = "aa"→"". Counting per character, not just presence, is what makes this work. A set would wrongly return"a". - Recording after the shrink loop. Record inside the
while, before you drops[left]. If you record after the loop, the window is already invalid. - Storing the substring every time. Building
s[left:right+1]inside the loop makes each record cost O(m). StorebestStartandbestLen, and slice once at the end. - Case sensitivity.
'A'and'a'are different. Index by character code, not byc - 'a'.
Say it in the interview
"Coverage is monotone. If a window covers t, any window containing it does too. So I use a sliding window. I grow the right edge until the window covers t, then shrink the left edge while it still does, recording the shortest. To check coverage in O(1), I keep need-counts per character and one counter called missing. A character only changes missing when its need crosses zero. Both pointers move forward at most m times, so it's O(m + n) time and O(1) space for a fixed alphabet."
Follow-ups interviewers ask
- "What if t is tiny but s is huge, with most characters irrelevant?" First build a filtered list of
(index, char)for only the characters that appear int. Then slide over that list. It's the same complexity, but much faster in practice. - "Count characters as a set: ignore duplicates in t." Initialise
need[c] = 1for each distinctc, andmissing= the number of distinct characters. Nothing else changes. - "Find the shortest subsequence of s containing t in order instead." That's a different problem (LeetCode 727). It needs DP or a two-direction scan, because order breaks the counting trick.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free