Minimum Window Substring

Smallest substring of s covering every character of t — variable-size sliding window with a 'missing' counter.

Hard
Time O(n + m) Space O(|Σ|)
LeetCode
5 min read
sliding-window string hash-map

Problem#

Given strings s and t, return the smallest window in s that contains every character of t (with multiplicity). Return "" if no such window exists.

Examples#

  • s = "ADOBECODEBANC", t = "ABC""BANC"
  • s = "a", t = "a""a"
  • s = "a", t = "aa"""

Constraints#

  • 1 <= s.length, t.length <= 10^5.

Hints#

Hint 1
Maintain a missing counter equal to t.length initially; decrement only when a needed character is actually still needed.

Approach#

Track need[c] = count of each character we still owe (negative = surplus). missing is the sum of positive need. Expand right; whenever the window covers t, contract left greedily and record the best window.

Solution#

Minimum Window Substring
class Solution {
public:
string minWindow(string s, string t) {
if (t.size() > s.size()) return "";
int need[256] = {0};
for (char c : t) ++need[(unsigned char)c];
int missing = t.size();
int bestL = 0, bestLen = INT_MAX;
int left = 0;
for (int right = 0; right < (int)s.size(); ++right) {
if (need[(unsigned char)s[right]]-- > 0) --missing;
while (missing == 0) {
if (right - left + 1 < bestLen) {
bestLen = right - left + 1;
bestL = left;
}
if (++need[(unsigned char)s[left++]] > 0) ++missing;
}
}
return bestLen == INT_MAX ? "" : s.substr(bestL, bestLen);
}
};

Editorial#

The dual-tracker pattern is the elegance: need may go negative (we have surplus of that character), but missing only tracks the deficit. Decrementing missing on add and incrementing on remove is gated by need crossing zero — that’s what allows surplus characters to be discarded freely while never under-counting needed ones. Each pointer advances at most n times → O(n + m).

Complexity#

  • Time: O(n + m).
  • Space: O(|Σ|).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.