-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathminWindowSubstring.js
49 lines (40 loc) · 1.44 KB
/
minWindowSubstring.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Sliding window: TC: O(m) + O(n) SC: O(m) + O(n)
function minWindowSubstring(windowStr, subStr) {
let windowStrCount = new Map();
let subStrCount = new Map();
let minLength = Number.MAX_VALUE;
let leftIndex = rightIndex = -1;
for(const ch of subStr) {
subStrCount.set(ch, (subStrCount.get(ch) || 0) + 1);
}
let having = 0; required = subStrCount.size;
let left = right = 0;
for(right = 0; right < windowStr.length; right++) {
let rightChar = windowStr.charAt(right);
windowStrCount.set(rightChar, (windowStrCount.get(right) || 0) +1);
if(subStrCount.has(rightChar) && subStrCount.get(rightChar) === windowStrCount.get(rightChar)) {
having++;
}
while(required === having) {
if(minLength > right-left+1) {
minLength = right-left+1;
leftIndex = left;
rightIndex = right;
}
let leftChar = windowStr.charAt(left);
windowStrCount.set(leftChar, windowStrCount.get(leftChar)-1);
if(subStrCount.has(leftChar) && subStrCount.get(leftChar) > windowStrCount.get(leftChar)) {
having--;
}
left++;
}
}
if(leftIndex === -1 || rightIndex === -1) {
return "";
} else {
return windowStr.substring(leftIndex, rightIndex+1);
}
}
let s ="ADOBECODEBANC";
let t= "ABC";
console.log(minWindowSubstring(s, t));