-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0076-minimum-window-substring.js
More file actions
46 lines (40 loc) · 1.42 KB
/
0076-minimum-window-substring.js
File metadata and controls
46 lines (40 loc) · 1.42 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
/**
* Minimum Window Substring
* Time Complexity: O(S + T)
* Space Complexity: O(1)
*/
var minWindow = function (s, t) {
const characterFrequencies = new Array(128).fill(0);
let charactersNeeded = t.length;
for (let charIterator = 0; charIterator < t.length; charIterator++) {
characterFrequencies[t.charCodeAt(charIterator)]++;
}
let minSubstringStart = 0;
let minSubstringLength = Infinity;
let windowBegin = 0;
for (let windowEnd = 0; windowEnd < s.length; windowEnd++) {
const currentCharCode = s.charCodeAt(windowEnd);
if (characterFrequencies[currentCharCode] > 0) {
charactersNeeded--;
}
characterFrequencies[currentCharCode]--;
while (charactersNeeded === 0) {
const currentWindowSize = windowEnd - windowBegin + 1;
if (currentWindowSize < minSubstringLength) {
minSubstringLength = currentWindowSize;
minSubstringStart = windowBegin;
}
const charToExitCode = s.charCodeAt(windowBegin);
characterFrequencies[charToExitCode]++;
if (characterFrequencies[charToExitCode] > 0) {
charactersNeeded++;
}
windowBegin++;
}
}
if (minSubstringLength === Infinity) {
return "";
} else {
return s.substring(minSubstringStart, minSubstringStart + minSubstringLength);
}
};