Skip to content

Commit 3725aff

Browse files
Jeehay28Jeehay28
authored andcommitted
Add minimum-window-substring solution in TS
1 parent 6c6f82b commit 3725aff

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// TC: O(m+ n), where m is the length of s, and n is the length of t
2+
// SC: O(n)
3+
4+
function minWindow(s: string, t: string): string {
5+
const tCnt = new Map<string, number>();
6+
const windowCnt = new Map<string, number>();
7+
8+
for (const ch of t) {
9+
tCnt.set(ch, (tCnt.get(ch) || 0) + 1);
10+
}
11+
12+
let left = 0;
13+
let validWindowKeySize = 0;
14+
let minStrLength = Infinity;
15+
let minLeft = 0;
16+
17+
for (let right = 0; right < s.length; right++) {
18+
const ch = s[right];
19+
20+
windowCnt.set(ch, (windowCnt.get(ch) || 0) + 1);
21+
22+
if (tCnt.has(ch) && tCnt.get(ch) === windowCnt.get(ch)) {
23+
validWindowKeySize++;
24+
}
25+
26+
// When windowCnt's keys include all the keys from tCnt
27+
while (tCnt.size === validWindowKeySize && left <= right) {
28+
// Update the minimum window details: start index (minLeft) and length (minStrLength)
29+
if (right - left + 1 < minStrLength) {
30+
minStrLength = right - left + 1;
31+
minLeft = left;
32+
}
33+
34+
// shrink the window by moving the left pointer
35+
const ch = s[left];
36+
windowCnt.set(ch, windowCnt.get(ch)! - 1);
37+
38+
if (tCnt.has(ch) && windowCnt.get(ch)! < tCnt.get(ch)!) {
39+
validWindowKeySize--;
40+
}
41+
42+
left++;
43+
}
44+
}
45+
46+
return minStrLength === Infinity
47+
? ""
48+
: s.slice(minLeft, minLeft + minStrLength);
49+
}

0 commit comments

Comments
 (0)