Minimum Window Substring
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given strings s and t, return the shortest substring of s that contains every character of t, including duplicates. If there is no such substring, return "".
Understand the problem
- A substring is a piece of
smade of neighbouring characters, with nothing skipped. - The piece must contain every character of
t, in any order, with other characters allowed in between. - Including duplicates: if
t = "AAB", the piece needs at least twoAs and oneB. - Among all pieces that qualify, return the shortest one. The tests guarantee there's only one shortest.
Example 1
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC""ADOBEC" (the first 6 letters) contains A, B and C, but it's 6 long. "BANC" near the end also contains all three, and it's only 4 long. Nothing shorter works.
Example 2
Input: s = "a", t = "a"
Output: "a"Example 3
Input: s = "a", t = "aa"
Output: ""t needs two as, but s has only one, so no piece of s can work.
Constraints
1 <= s.length, t.length <= 10^5sandtcontain English letters.
Note
Aim for O(m + n) time, where m and n are the lengths of s and t.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Grow a window on the right until it contains everything t needs, then shrink it from the left as much as possible while it still does, and remember the shortest one.
The naive approach (and why it's slow)
Check every substring of s and test whether it contains all of t's characters. There are about m²/2 substrings, and each test takes time, so this is O(m²) at best. With s up to 100,000 characters, that's billions of steps.
The key insight
This is the sliding window template with a twist: we're looking for the shortest valid window, not the longest.
- Expand (
right++) until the window coverst. - Then contract (
left++) as long as it still coverst. Each valid window we pass through is a candidate answer. - When it stops covering
t, go back to expanding.
The tricky part is checking "does the window cover t?" quickly. We use one hash map, need, plus one number, missing:
need[c]= how many morecthe window still has to get. It starts as the counts int.missing= how many characters oftthe window still lacks in total. It starts ast.length.- When
centers the window: ifneed[c] > 0, this copy was really needed, somissing--. Thenneed[c]--either way. need[c] < 0means the window has extra copies ofc. Those are safe to drop from the left.- The window covers
texactly whenmissing === 0.
Step by step
s = "ADOBECODEBANC", t = "ABC" → need = {A:1, B:1, C:1}, missing = 3.
1. Expand until it covers t:
right | Char | Was it needed? | missing | Window |
|---|---|---|---|---|
| 0 | A | yes | 2 | A |
| 1 | D | no | 2 | AD |
| 2 | O | no | 2 | ADO |
| 3 | B | yes | 1 | ADOB |
| 4 | E | no | 1 | ADOBE |
| 5 | C | yes | 0 ✅ | ADOBEC |
2. Shrink: the leftmost char is A, which is needed (need[A] = 0, not extra). We can't drop it for free. Record ADOBEC (length 6) as the best so far. Then drop the A on purpose: missing = 1, left = 1.
3. Expand again until we find another A: right moves through O, D, E, B and reaches the A at index 10. missing = 0 again. Window: DOBECODEBA.
4. Shrink: D, O are extra (not needed), the B at index 3 is extra (there's another B at index 9), E is extra, and then the C at index 5 is needed. So left stops there. Window: CODEBA (length 6). Not shorter. Drop the C: missing = 1.
5. Expand again to the C at index 12. Window: ODEBANC. Shrink: O, D, E are extra. Stop at B (needed). Window: BANC (length 4), the new best.
right has reached the end. Answer: "BANC".
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(m + n). Counting
tis O(n). Thenrightcrossessonce, andleftcrosses it at most once. Each step does constant work. - Memory: O(k) for the counts, where
kis the number of different characters.
Common mistakes
- Comparing two full count maps on every step to check coverage. That's correct but slow. The single
missingnumber makes the check instant. - Ignoring duplicates in
t. Witht = "AA", oneAisn't enough. Counting with a map handles this automatically. - Recording the window before shrinking it. Shrink first, then record, so you record the shortest version.
- Returning the first valid window. It's often not the shortest. Keep going to the end of
s.
Going deeper
This is considered the "final boss" of sliding window problems. If you can explain the need / missing bookkeeping clearly, you can handle any variant: "smallest window with all distinct characters", "find all anagrams of t in s", and so on.
Reference solution
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
export default function minWindow(s, t) {
// need[c] = how many more c the window still has to get.
// Below zero means the window has EXTRA copies of c (safe to drop).
const need = new Map()
for (const char of t) need.set(char, (need.get(char) ?? 0) + 1)
let missing = t.length // how many characters of t the window still lacks
let left = 0
let bestStart = 0
let bestLength = Infinity
for (let right = 0; right < s.length; right++) {
// Expand: s[right] enters the window.
const char = s[right]
if ((need.get(char) ?? 0) > 0) missing-- // this copy was really needed
need.set(char, (need.get(char) ?? 0) - 1)
if (missing > 0) continue // not covering t yet: keep expanding
// Shrink: drop extra characters from the left while still covering t.
while (need.get(s[left]) < 0) {
need.set(s[left], need.get(s[left]) + 1)
left++
}
// s[left..right] is the shortest valid window ending at right.
if (right - left + 1 < bestLength) {
bestStart = left
bestLength = right - left + 1
}
// Drop one NEEDED character on purpose, so we go looking for a shorter window.
need.set(s[left], need.get(s[left]) + 1)
missing++
left++
}
return bestLength === Infinity ? '' : s.slice(bestStart, bestStart + bestLength)
}export default function minWindow(s: string, t: string): string {
// need[c] = how many more c the window still has to get.
// Below zero means the window has EXTRA copies of c (safe to drop).
const need = new Map<string, number>()
for (const char of t) need.set(char, (need.get(char) ?? 0) + 1)
const count = (char: string) => need.get(char) ?? 0
let missing = t.length // how many characters of t the window still lacks
let left = 0
let bestStart = 0
let bestLength = Infinity
for (let right = 0; right < s.length; right++) {
// Expand: s[right] enters the window.
const char = s[right]
if (count(char) > 0) missing-- // this copy was really needed
need.set(char, count(char) - 1)
if (missing > 0) continue // not covering t yet: keep expanding
// Shrink: drop extra characters from the left while still covering t.
while (count(s[left]) < 0) {
need.set(s[left], count(s[left]) + 1)
left++
}
// s[left..right] is the shortest valid window ending at right.
if (right - left + 1 < bestLength) {
bestStart = left
bestLength = right - left + 1
}
// Drop one NEEDED character on purpose, so we go looking for a shorter window.
need.set(s[left], count(s[left]) + 1)
missing++
left++
}
return bestLength === Infinity ? '' : s.slice(bestStart, bestStart + bestLength)
}from collections import Counter
def min_window(s: str, t: str) -> str:
# need[c] = how many more c the window still has to get.
# Below zero means the window has EXTRA copies of c (safe to drop).
need = Counter(t)
missing = len(t) # how many characters of t the window still lacks
left = 0
best_start, best_length = 0, float("inf")
for right, char in enumerate(s):
# Expand: s[right] enters the window.
if need[char] > 0:
missing -= 1 # this copy was really needed
need[char] -= 1
if missing > 0:
continue # not covering t yet: keep expanding
# Shrink: drop extra characters from the left while still covering t.
while need[s[left]] < 0:
need[s[left]] += 1
left += 1
# s[left..right] is the shortest valid window ending at right.
if right - left + 1 < best_length:
best_start, best_length = left, right - left + 1
# Drop one NEEDED character on purpose, so we go looking for a shorter window.
need[s[left]] += 1
missing += 1
left += 1
return "" if best_length == float("inf") else s[best_start : best_start + best_length]