Skip to content

Commit cb08be6

Browse files
committed
Minimum Window Substring
1 parent d83d1f3 commit cb08be6

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

76-minimum-window-substring.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/minimum-window-substring/
3+
4+
Given two strings s and t, return the minimum window in s which will contain all the characters in t.
5+
If there is no such window in s that covers all characters in t, return the empty string "".
6+
Note that If there is such a window, it is guaranteed that there will always be only one unique minimum window in s.
7+
8+
Example 1:
9+
Input: s = "ADOBECODEBANC", t = "ABC"
10+
Output: "BANC"
11+
12+
Example 2:
13+
Input: s = "a", t = "a"
14+
Output: "a"
15+
16+
Constraints:
17+
1 <= s.length, t.length <= 105
18+
s and t consist of English letters.
19+
20+
Follow up: Could you find an algorithm that runs in O(n) time?
21+
"""
22+
class Solution:
23+
def minWindow(self, s: str, t: str) -> str:
24+
count = {}
25+
for c in t:
26+
count[c] = count.get(c, 0) + 1
27+
28+
# counter represents the number of chars of t to be found in s.
29+
start, end, min_len, min_start, counter = 0, 0, float('inf'), 0, len(t)
30+
31+
while end < len(s):
32+
33+
# If char in s exists in t, decrease counter
34+
if count.get(s[end], 0) > 0:
35+
counter -= 1
36+
37+
# Decrease count[s[end]]. If char does not exist in t, count[s[end]] will be negative.
38+
count[s[end]] = count.get(s[end], 0) - 1
39+
40+
end += 1
41+
42+
# When we found a valid window, move start to find smaller window.
43+
while counter == 0:
44+
45+
if (end - start) < min_len:
46+
min_len = end - start
47+
min_start = start
48+
49+
count[s[start]] += 1
50+
51+
# When char exists in t, increase counter.
52+
if count[s[start]] > 0:
53+
counter += 1
54+
55+
start += 1
56+
57+
return s[min_start: min_start + min_len] if min_len != float('inf') else ""

0 commit comments

Comments
 (0)