Skip to content

Commit d0717a2

Browse files
committed
Minimum Window Substring
1 parent e203ec2 commit d0717a2

File tree

2 files changed

+69
-1
lines changed

2 files changed

+69
-1
lines changed

minimum-window-substring.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
2+
3+
The testcases will be generated such that the answer is unique.
4+
5+
A substring is a contiguous sequence of characters within the string. */
6+
7+
/**
8+
* @param {string} s
9+
* @param {string} t
10+
* @return {string}
11+
*/
12+
var minWindow = function(s, t) {
13+
const map = new Map()
14+
for (let i = 0; i < t.length; i++) {
15+
map.set(t[i], (map.get(t[i]) || 0) + 1)
16+
}
17+
18+
let count = 1
19+
let start = 0
20+
while (start < s.length && !map.has(s[start])) {
21+
start++
22+
}
23+
if (start === s.length) {
24+
return ''
25+
}
26+
if (t.length === 1) {
27+
return s[start]
28+
}
29+
map.set(s[start], map.get(s[start]) - 1)
30+
31+
let minStart = start
32+
let minEnd = s.length
33+
34+
for (end = start + 1; end < s.length; end++) {
35+
if (map.has(s[end])) {
36+
let endCount = map.get(s[end])
37+
map.set(s[end], --endCount)
38+
// endCount < 0 means there are too many s[end] within the window.
39+
if (endCount >= 0) {
40+
count++
41+
}
42+
43+
// There could be too may s[start] within the window.
44+
// So after dumping the first s[start] the window might still be full.
45+
while (count === t.length) {
46+
if (end - start < minEnd - minStart) {
47+
minStart = start
48+
minEnd = end
49+
}
50+
51+
let startCount = map.get(s[start])
52+
map.set(s[start], ++startCount)
53+
if (startCount > 0) {
54+
// the window is not full anymore
55+
count--
56+
}
57+
58+
start++
59+
while (!map.has(s[start])) {
60+
start++
61+
}
62+
}
63+
}
64+
}
65+
66+
return minEnd === s.length ? '' : s.slice(minStart, minEnd + 1)
67+
};

readme.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@
1818
14. Search in Rotated Sorted Array - (https://leetcode.com/problems/search-in-rotated-sorted-array/)
1919
15. 3Sum - (https://leetcode.com/problems/3sum/)
2020
16. Container With Most Water - (https://leetcode.com/problems/container-with-most-water/)
21-
17. Longest Substring Without Repeating Characters - (https://leetcode.com/problems/longest-substring-without-repeating-characters/)
21+
17. Longest Substring Without Repeating Characters - (https://leetcode.com/problems/longest-substring-without-repeating-characters/)
22+
18. Minimum Window Substring - (https://leetcode.com/problems/minimum-window-substring/)

0 commit comments

Comments
 (0)