Minimum Window Substring
Hard
Topics
Given two strings s and t, return the smallest substring of s that contains every character of t (including duplicates). If there is no such window, return the empty string "". When several windows share the minimum length, return the one with the smallest starting index.
Example 1
ABC, counting duplicates, and is the shortest that does — BANC.Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC"
Example 2
Input: s = "a", t = "a" Output: "a"
Example 3
Input: s = "a", t = "aa" Output: ""
Constraints
- 1 <= s.length <= 16
- 1 <= t.length <= 6
- s and t consist of lowercase and uppercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The brute force is to take every substring of s, check whether it covers t, and keep the shortest that does. There are O(n^2) substrings and each check costs O(n), so that is O(n^3) — fine to state, useless to run.
The first real improvement is noticing that the check is incremental. If you extend a window one character to the right, you do not need to recount it; you adjust one tally. That alone drops the check to O(1) amortised.
The second is the observation that makes this a window rather than a search. Suppose a window [left, right] already covers t. Then every wider window starting at the same left also covers t and is longer, so it cannot be the answer. The only useful move is to shrink from the left. And once shrinking breaks coverage, extending left further is hopeless too — you must grow right again. So each pointer only ever moves forward, and the whole scan is linear.
The bookkeeping trick that keeps it O(1) per step is to track a single number, missing: how many characters of t are still unmatched, counting multiplicity. Coverage is then not a map comparison but the test missing == 0.
The one subtlety is that a window may hold surplus copies of a character. Decrement missing only when the copy you just consumed was actually needed — that is, when the stored requirement for it was still positive.
Approach
- Build
need, a count per character oft. Setmissing = len(t), which counts duplicates:t = "AABC"needs two A's, not one. - Advance
rightacrosss. For each character, decrement its entry inneed. If that entry was positive before the decrement, the copy was genuinely needed, so decrementmissingtoo. A surplus copy drives the entry negative and leavesmissingalone, which is exactly how the surplus is remembered. - While
missing == 0the window is valid. Record it if it beats the best so far, then shrink: incrementneedfor the character atleft, and if that entry becomes positive the character was load-bearing, somissinggoes back up and the window stops being valid. - Return the best window, or the empty string if none was ever valid.
A negative entry in need means surplus, zero means exactly met, positive means still owed. That sign convention is doing the work that a second map would otherwise do.
Dry Run
s = "ADOBECODEBANC", t = "ABC". So need = {A:1, B:1, C:1} and missing = 3.
right ch need[ch] missing
0 A 0 2 needed
1 D -1 2 surplus
2 O -1 2 surplus
3 B 0 1 needed
4 E -1 1 surplus
5 C 0 0 needed
-> valid [0..5] "ADOBEC" len 6 BEST
-> drop A at 0: need[A]=1 POSITIVE, missing=1, invalid
6 O -2 1
7 D -2 1
8 E -2 1
9 B -1 1 surplus B, missing unchanged
10 A 0 0 needed
-> valid [1..10] "DOBECODEBA" len 10 not better
-> drop D: -1 surplus, still valid
-> valid [2..10] "OBECODEBA" len 9 not better
-> drop O: -1 surplus, still valid
-> valid [3..10] "BECODEBA" len 8 not better
-> drop B: 0 surplus, still valid
-> valid [4..10] "ECODEBA" len 7 not better
-> drop E: -1 surplus, still valid
-> valid [5..10] "CODEBA" len 6 ties 6, best unchanged
-> drop C at 5: need[C]=1 POSITIVE, missing=1, invalid
11 N -1 1
12 C 0 0 needed
-> valid [6..12] "ODEBANC" len 7 not better
-> drop O: 0 surplus, still valid
-> valid [7..12] "DEBANC" len 6 ties 6, best unchanged
-> drop D: 0 surplus, still valid
-> valid [8..12] "EBANC" len 5 BEST
-> drop E: 0 surplus, still valid
-> valid [9..12] "BANC" len 4 BEST
-> drop B at 9: need[B]=1 POSITIVE, missing=1, invalidAnswer "BANC". Two things the trace makes visible. The long shrink after right=10 walks left from 1 to 6 in one burst, and the answer improves twice in the final shrink — through "EBANC" before reaching "BANC" — which is why the record step has to sit inside the shrink loop rather than after it. And left never moves backwards anywhere in the run, which is the property that buys the linear bound.
Complexity
- Time — O(|s| + |t|): building
needis O(|t|). Thenrightadvances |s| times andleftadvances at most |s| times, and neither ever retreats, so the scan is O(|s|) even though it is written as a loop inside a loop. Each step is O(1) because coverage is the integer testmissing == 0rather than a map comparison. Compare the O(n^3) enumerate-every-substring opener. - Space — O(|s| + |t|): the
needmap holds at most one entry per distinct character oft, plus the surplus entries created by characters ofs— so O(|t|) for what is owed and O(|s|) in the worst case for what is in surplus. With the problem's constraint of uppercase and lowercase letters only this is bounded by the 52-letter alphabet, i.e. O(1), and saying so is the better answer if you have established the alphabet is fixed.
Common Pitfalls
- Setting
missing = len(need)instead oflen(t). That ignores duplicates, sot = "AABC"would be satisfied by a window holding a single A. - Decrementing
missingon every matching character rather than only when the requirement was still positive. A window with three A's where two are needed would then report coverage one character early. - Shrinking with
ifrather thanwhile. After a window becomes valid there may be several removable characters at the left, and stopping after one leaves a window that is valid but not minimal. - Recording the answer after shrinking instead of before. The window is minimal at the moment just before it stops being valid, so measure it inside the shrink loop.
- Storing the best substring itself on every improvement. Keep the start index and length and slice once at the end, or the copying turns an O(n) scan into O(n^2) in the worst case.
- Returning some sentinel rather than
""when no window coverst, including the case|t| > |s|.
Full Solution — all languages
class Solution:
def minWindow(self, s, t):
if not t:
return ""
need = {}
for c in t:
need[c] = need.get(c, 0) + 1
required = len(need)
have = {}
formed = 0
l = 0
best_len = float('inf')
best_l = 0
for r in range(len(s)):
c = s[r]
if c in need:
have[c] = have.get(c, 0) + 1
if have[c] == need[c]:
formed += 1
while formed == required:
if r - l + 1 < best_len:
best_len = r - l + 1
best_l = l
lc = s[l]
if lc in need:
have[lc] -= 1
if have[lc] < need[lc]:
formed -= 1
l += 1
return "" if best_len == float('inf') else s[best_l:best_l + best_len]import java.util.*;
class Solution {
public String minWindow(String s, String t) {
if (t.isEmpty()) return "";
Map<Character,Integer> need = new HashMap<>(), have = new HashMap<>();
for (char c : t.toCharArray()) need.put(c, need.getOrDefault(c, 0) + 1);
int required = need.size(), formed = 0, l = 0, bestLen = Integer.MAX_VALUE, bestL = 0;
for (int r = 0; r < s.length(); r++) {
char c = s.charAt(r);
if (need.containsKey(c)) {
have.put(c, have.getOrDefault(c, 0) + 1);
if (have.get(c).equals(need.get(c))) formed++;
}
while (formed == required) {
if (r - l + 1 < bestLen) {
bestLen = r - l + 1;
bestL = l;
}
char lc = s.charAt(l);
if (need.containsKey(lc)) {
have.put(lc, have.get(lc) - 1);
if (have.get(lc) < need.get(lc)) formed--;
}
l++;
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestL, bestL + bestLen);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string minWindow(string s, string t) {
if (t.empty()) return "";
unordered_map<char,int> need, have;
for (char c : t) need[c]++;
int required = need.size(), formed = 0, l = 0, bestLen = INT_MAX, bestL = 0;
for (int r = 0; r < (int)s.size(); r++) {
char c = s[r];
if (need.count(c)) {
have[c]++;
if (have[c] == need[c]) formed++;
}
while (formed == required) {
if (r - l + 1 < bestLen) {
bestLen = r - l + 1;
bestL = l;
}
char lc = s[l];
if (need.count(lc)) {
have[lc]--;
if (have[lc] < need[lc]) formed--;
}
l++;
}
}
return bestLen == INT_MAX ? "" : s.substr(bestL, bestLen);
}
};/**
* @param {string} s
* @param {string} t
* @return {string}
*/ var minWindow = function(s, t) {
if (!t.length) return "";
const need = {};
for (const c of t) need[c] = (need[c] || 0) + 1;
const required = Object.keys(need).length;
const have = {};
let formed = 0, l = 0, bestLen = Infinity, bestL = 0;
for (let r = 0; r < s.length; r++) {
const c = s[r];
if (need[c] !== undefined) {
have[c] = (have[c] || 0) + 1;
if (have[c] === need[c]) formed++;
}
while (formed === required) {
if (r - l + 1 < bestLen) {
bestLen = r - l + 1;
bestL = l;
}
const lc = s[l];
if (need[lc] !== undefined) {
have[lc]--;
if (have[lc] < need[lc]) formed--;
}
l++;
}
}
return bestLen === Infinity ? "" : s.substr(bestL, bestLen);
};