Minimum window substring
Hard TimeO(n) SpaceO(k)
Given strings s and t, return the shortest substring of s that holds every character of t, counting repeats, or the empty string "" when no substring does. A character t asks for twice must appear twice in the answer. The answer may hold characters t does not ask for — only its length matters — and where two substrings tie for shortest, either is correct.
Examples
Example 1
- Input
- s = "ADOBECODEBANC"t = "ABC"
- Output
- Four characters holding B, A and C; the first window that worked,
"BANC""ADOBEC", needed six.
Example 2
- Input
- s = "a"t = "aa"
- Output
""tasks for twoaandsholds one, so no substring can cover it.
The Code
function minWindow(s, t) {
const need = new Map();
for (let i = 0; i < t.length; i++) {
need.set(t[i], (need.get(t[i]) || 0) + 1);
}
let missing = t.length;
let start = 0;
let bestStart = 0;
let bestLength = -1;
for (let end = 0; end < s.length; end++) {
const ch = s[end];
if (need.has(ch)) {
if (need.get(ch) > 0) missing--;
need.set(ch, need.get(ch) - 1);
}
while (missing === 0) {
if (bestLength === -1 || end - start + 1 < bestLength) {
bestLength = end - start + 1;
bestStart = start;
}
const left = s[start];
if (need.has(left)) {
need.set(left, need.get(left) + 1);
if (need.get(left) > 0) missing++;
}
start++;
}
}
return bestLength === -1 ? "" : s.slice(bestStart, bestStart + bestLength);
}
minWindow("ADOBECODEBANC", "ABC");Done
The first 14 calls, of 32. This one does not fit on a page.
More like this
All strings examples (13) →- Reverse words Split on whitespace, walk backwards, join again.
- Valid anagram Count letters up with one word, down with the other.
- Common prefix Start with the whole first word, shrink until everything matches.
- Run-length encoding Collapse each run of repeats into a character and a count.
- First unique char Count every character first, then find the earliest with count 1.
- Longest unique substring A sliding window that jumps forward past any repeat.