-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathMinimumWindowSubstring.js
More file actions
42 lines (35 loc) · 933 Bytes
/
MinimumWindowSubstring.js
File metadata and controls
42 lines (35 loc) · 933 Bytes
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
/*
* Author: Mayank
* Minimum Window Substring implementation in JavaScript
* Finds the smallest substring of s that contains all characters of t.
*/
function minWindowSubstring(s, t) {
if (t.length > s.length) return ''
const need = {}
for (let char of t) {
need[char] = (need[char] || 0) + 1
}
let left = 0
let count = t.length
let minLen = Infinity
let minStart = 0
for (let right = 0; right < s.length; right++) {
if (need[s[right]] !== undefined) {
if (need[s[right]] > 0) count--
need[s[right]]--
}
while (count === 0) {
if (right - left + 1 < minLen) {
minLen = right - left + 1
minStart = left
}
if (need[s[left]] !== undefined) {
need[s[left]]++
if (need[s[left]] > 0) count++
}
left++
}
}
return minLen === Infinity ? '' : s.substring(minStart, minStart + minLen)
}
export { minWindowSubstring }