Minimum Window Substring
Pattern: Sliding window: variable size
Keep a count of how many of each character of t the window still needs, plus one number for the total still missing. Grow until nothing is missing, then shrink from the left while that stays true.
The problem
You are given two strings, s and t. Return the shortest block of neighbouring characters of s that contains every
character of t, counting repeats (if t has two as, the block needs two as). If there is no such block, return
the empty string. For example, "ADOBECODEBANC" with t = "ABC" gives "BANC", and "a" with t = "aa" gives "".
The function name minWindow matches LeetCode, which promises that the answer is unique. This guide's tests also
include ties, and on a tie the code returns the leftmost shortest block. Use the link above for the exact statement.
Think first
- How do you check, in O(1), whether the window covers
t, including repeated characters? - Once it covers
t, is it ever worth growing it more before shrinking? - When you drop
s[left], how do you know whether that broke the cover?
Hints
Brute force, and why it fails
Check every block of s against the counts of t: O(n²) blocks, each checked in O(alphabet). The window is
O(n + m) for s of length n and t of length m.
The key insight
"Covers t" only gets easier as the window grows, so this is the shortest-window template. The need counts, allowed to
go negative, plus the single number missing make each add and drop O(1).
Dry run
| missing | 3 |
|---|
s = ADOBECODEBANC and t = ABC. need starts as A 1, B 1, C 1 and missing = 3. Grow until missing is 0.
The plan
need[c] = count of c in t, for every c
missing = length(t)
left = 0, bestStart = 0, bestLen = infinity
for right from 0 to n - 1:
if need[s[right]] > 0: missing = missing - 1
need[s[right]] = need[s[right]] - 1
while missing == 0:
if right - left + 1 < bestLen:
bestLen = right - left + 1, bestStart = left
need[s[left]] = need[s[left]] + 1
if need[s[left]] > 0: missing = missing + 1
left = left + 1
return "" if bestLen is infinity else s[bestStart .. bestStart + bestLen - 1]
Complexity
- Time
O(n + m)- Space
O(alphabet)
Counting t is O(m). Each edge of the window moves at most n times. need has one slot per possible character.
Edge cases
tlonger thans, or with a characterslacks:"".sequal tot: the whole string.- Repeats in
t, as in"aaflslflsldkalskaaa"witht = "aaa": the window needs threeas, and the answer is"aaa".
I've built my logic, show the code
Java
class Solution {
public String minWindow(String s, String t) {
int[] need = new int[128]; // how many more of each character the window still needs
for (int i = 0; i < t.length(); i++) need[t.charAt(i)]++;
int missing = t.length(); // characters of t not yet covered
int left = 0, bestStart = 0, bestLen = Integer.MAX_VALUE;
for (int right = 0; right < s.length(); right++) {
if (need[s.charAt(right)]-- > 0) missing--;
while (missing == 0) { // window covers t: record it, then shrink
if (right - left + 1 < bestLen) {
bestLen = right - left + 1;
bestStart = left;
}
if (++need[s.charAt(left)] > 0) missing++; // dropped a character the window needed
left++;
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + bestLen);
}
}C++
class Solution {
public:
string minWindow(string s, string t) {
vector<int> need(128, 0); // how many more of each character the window still needs
for (unsigned char c : t) need[c]++;
int missing = static_cast<int>(t.size()); // characters of t not yet covered
int left = 0, bestStart = 0, bestLen = INT_MAX;
for (int right = 0; right < static_cast<int>(s.size()); right++) {
if (need[static_cast<unsigned char>(s[right])]-- > 0) missing--;
while (missing == 0) { // window covers t: record it, then shrink
if (right - left + 1 < bestLen) {
bestLen = right - left + 1;
bestStart = left;
}
if (++need[static_cast<unsigned char>(s[left])] > 0) missing++; // dropped a needed character
left++;
}
}
return bestLen == INT_MAX ? "" : s.substr(bestStart, bestLen);
}
};Python
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = {} # how many more of each character the window still needs
for c in t:
need[c] = need.get(c, 0) + 1
missing = len(t) # characters of t not yet covered
left, best_start, best_len = 0, 0, len(s) + 1
for right, c in enumerate(s):
if need.get(c, 0) > 0:
missing -= 1
need[c] = need.get(c, 0) - 1
while missing == 0: # window covers t: record it, then shrink
if right - left + 1 < best_len:
best_len, best_start = right - left + 1, left
need[s[left]] += 1
if need[s[left]] > 0:
missing += 1 # dropped a character the window needed
left += 1
return "" if best_len == len(s) + 1 else s[best_start:best_start + best_len]Common mistakes
- Checking the cover by comparing two full count tables each step, which is O(alphabet) per step instead of O(1).
- Treating
tas a set and ignoring repeats. - Lowering
missingfor every arriving character, even spare copies that fill no gap. - Updating the best with
≤, which returns a later block on a tie instead of the leftmost.