Skip to content

Commit 5176fd8

Browse files
committed
Add minimum-window-substring solution
1 parent de0fb83 commit 5176fd8

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* @param {string} s
3+
* @param {string} t
4+
* @return {string}
5+
*/
6+
7+
// 🚀 sliding window + two pointer approach
8+
9+
// 🕒 Time Complexity: O(n), where n is the length of s
10+
// The inner while loop shrinks the window from the left side but never exceeds the total number of characters in s
11+
12+
// 🗂 Space Complexity: O(m) (or worst case O(n)), where n is the length of t
13+
14+
var minWindow = function (s, t) {
15+
// early return for the critical edge case
16+
if (s.length < t.length) {
17+
return "";
18+
}
19+
20+
let windowCnt = new Map();
21+
let charCnt = new Map();
22+
let minStart = 0;
23+
let minEnd = s.length; // set this to an out-of-bounds value initially
24+
25+
let formed = 0;
26+
let left = 0;
27+
28+
// initialize charCount
29+
// 🔢 t = "ABC", charCount = { A: 1, B: 1, C: 1 }
30+
for (const ch of t) {
31+
charCnt.set(ch, (charCnt.get(ch) || 0) + 1);
32+
}
33+
34+
// expand the windowCnt
35+
for (let right = 0; right < s.length; right++) {
36+
const char = s[right];
37+
38+
windowCnt.set(char, (windowCnt.get(char) || 0) + 1);
39+
40+
if (charCnt.has(char) && charCnt.get(char) === windowCnt.get(char)) {
41+
formed += 1;
42+
}
43+
44+
// shrink the window by moving the left pointer
45+
while (formed === charCnt.size) {
46+
if (right - left < minEnd - minStart) {
47+
minStart = left;
48+
minEnd = right;
49+
}
50+
51+
const char = s[left];
52+
windowCnt.set(char, windowCnt.get(char) - 1);
53+
54+
if (charCnt.has(char) && windowCnt.get(char) < charCnt.get(char)) {
55+
formed -= 1;
56+
}
57+
left += 1;
58+
}
59+
}
60+
61+
return minEnd === s.length ? "" : s.slice(minStart, minEnd + 1);
62+
};
63+

0 commit comments

Comments
 (0)