Leetcode•Aug 06, 2025
Minimum Window Substring
Hazrat Ali
Leetcode
The testcases will be generated such that the answer is unique.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa" Output: "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string.
Solution
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
const minWindow = (s, t) => {
const map = {};
for (let c of t) {
map[c] = ~~map[c] + 1;
}
let start = 0;
let size = Infinity;
let counter = t.length;
for (let i = 0, j = 0; j < s.length; j++) {
if (map[s[j]]-- > 0) {
counter--;
}
while (counter === 0) {
if (j - i + 1 < size) {
size = j - i + 1;
start = i;
}
if (map[s[i++]]++ === 0) {
counter++;
}
}
}
return size === Infinity ? '' : s.substr(start, size);
};