Skip to content

Commit 139e6c1

Browse files
committed
minimum window substring solution
1 parent 17a194e commit 139e6c1

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
function minWindow(s: string, t: string): string {
2+
const m = s.length;
3+
const n = t.length;
4+
5+
if (m < n) return "";
6+
7+
let windowStart = 0;
8+
let minLen = Infinity;
9+
let substring = "";
10+
11+
let requiredChar = n;
12+
13+
const countCharMap = new Map<string, number>();
14+
for (const ch of t) {
15+
countCharMap.set(ch, (countCharMap.get(ch) || 0) + 1);
16+
}
17+
18+
for (let windowEnd = 0; windowEnd < m; windowEnd++) {
19+
const endChar = s[windowEnd];
20+
21+
if (countCharMap.has(endChar)) {
22+
if (countCharMap.get(endChar)! > 0) requiredChar--;
23+
countCharMap.set(endChar, (countCharMap.get(endChar) || 0) - 1);
24+
}
25+
26+
while (requiredChar === 0) {
27+
const currentLen = windowEnd - windowStart + 1;
28+
if (currentLen < minLen) {
29+
minLen = currentLen;
30+
substring = s.substring(windowStart, windowEnd + 1);
31+
}
32+
33+
const startChar = s[windowStart];
34+
windowStart++;
35+
36+
if (countCharMap.has(startChar)) {
37+
countCharMap.set(startChar, (countCharMap.get(startChar) || 0) + 1);
38+
if (countCharMap.get(startChar)! > 0) requiredChar++;
39+
}
40+
}
41+
}
42+
43+
return substring;
44+
}

0 commit comments

Comments
 (0)