Overview
Given two strings s and t, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
Constraints
1 <= s.length, t.length <= 100,000sandtconsist of uppercase and lowercase English letters.- Must run in O(n) time.
Examples
minWindow("ADOBECODEBANC", "ABC");
// => "BANC"minWindow("a", "a");
// => "a"
minWindow("a", "aa");
// => "" (not enough 'a's)Solution
Reveal solution
function minWindow(s, t) {
const need = {};
for (const c of t) need[c] = (need[c] || 0) + 1;
let have = 0, required = Object.keys(need).length;
const window = {};
let left = 0, minLen = Infinity, minStart = 0;
for (let right = 0; right < s.length; right++) {
const c = s[right];
window[c] = (window[c] || 0) + 1;
if (need[c] && window[c] === need[c]) have++;
while (have === required) {
if (right - left + 1 < minLen) {
minLen = right - left + 1;
minStart = left;
}
const lc = s[left];
window[lc]--;
if (need[lc] && window[lc] < need[lc]) have--;
left++;
}
}
return minLen === Infinity ? "" : s.substring(minStart, minStart + minLen);
}Sliding window: expand right to include all required characters, then shrink left to find the minimum window. Track how many unique characters are satisfied.
Resources
shortest-substring-containing-characters.js
Shortest Substring Containing Characters
hardcodingAlgorithmsSliding Window
Overview
Given two strings s and t, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
Constraints
1 <= s.length, t.length <= 100,000sandtconsist of uppercase and lowercase English letters.- Must run in O(n) time.
Examples
minWindow("ADOBECODEBANC", "ABC");
// => "BANC"minWindow("a", "a");
// => "a"
minWindow("a", "aa");
// => "" (not enough 'a's)Solution
Reveal solution
function minWindow(s, t) {
const need = {};
for (const c of t) need[c] = (need[c] || 0) + 1;
let have = 0, required = Object.keys(need).length;
const window = {};
let left = 0, minLen = Infinity, minStart = 0;
for (let right = 0; right < s.length; right++) {
const c = s[right];
window[c] = (window[c] || 0) + 1;
if (need[c] && window[c] === need[c]) have++;
while (have === required) {
if (right - left + 1 < minLen) {
minLen = right - left + 1;
minStart = left;
}
const lc = s[left];
window[lc]--;
if (need[lc] && window[lc] < need[lc]) have--;
left++;
}
}
return minLen === Infinity ? "" : s.substring(minStart, minStart + minLen);
}Sliding window: expand right to include all required characters, then shrink left to find the minimum window. Track how many unique characters are satisfied.
Resources
NameTopicDifficulty
103 of 103 problems