forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJeehay28.js
More file actions
63 lines (48 loc) ยท 1.55 KB
/
Jeehay28.js
File metadata and controls
63 lines (48 loc) ยท 1.55 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
// ๐ sliding window + two pointer approach
// ๐ Time Complexity: O(n), where n is the length of s
// The inner while loop shrinks the window from the left side but never exceeds the total number of characters in s
// ๐ Space Complexity: O(m) (or worst case O(n)), where n is the length of t
var minWindow = function (s, t) {
// early return for the critical edge case
if (s.length < t.length) {
return "";
}
let windowCnt = new Map();
let charCnt = new Map();
let minStart = 0;
let minEnd = s.length; // set this to an out-of-bounds value initially
let formed = 0;
let left = 0;
// initialize charCount
// ๐ข t = "ABC", charCount = { A: 1, B: 1, C: 1 }
for (const ch of t) {
charCnt.set(ch, (charCnt.get(ch) || 0) + 1);
}
// expand the windowCnt
for (let right = 0; right < s.length; right++) {
const char = s[right];
windowCnt.set(char, (windowCnt.get(char) || 0) + 1);
if (charCnt.has(char) && charCnt.get(char) === windowCnt.get(char)) {
formed += 1;
}
// shrink the window by moving the left pointer
while (formed === charCnt.size) {
if (right - left < minEnd - minStart) {
minStart = left;
minEnd = right;
}
const char = s[left];
windowCnt.set(char, windowCnt.get(char) - 1);
if (charCnt.has(char) && windowCnt.get(char) < charCnt.get(char)) {
formed -= 1;
}
left += 1;
}
}
return minEnd === s.length ? "" : s.slice(minStart, minEnd + 1);
};