-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimum_window_substring.py
More file actions
88 lines (62 loc) · 2.63 KB
/
minimum_window_substring.py
File metadata and controls
88 lines (62 loc) · 2.63 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'''
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 "".
The testcases will be generated such that the answer is unique.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
Constraints:
m == s.length
n == t.length
1 <= m, n <= 105
s and t consist of uppercase and lowercase English letters.
Follow up: Could you find an algorithm that runs in O(m + n) time?
'''
from collections import Counter
class Solution:
def __call__(self, s: str, t: str) -> str:
counter = Counter(t)
required_char_countdown = len(t)
if required_char_countdown == 0:
return ""
il = 0
res: None|str = None
for i_char in range(len(s)):
if s[i_char] in counter:
counter[s[i_char]] -= 1
if counter[s[i_char]] >= 0:
required_char_countdown -= 1
if required_char_countdown == 0:
while il<i_char:
char = s[il]
if char in counter:
if counter[char] < 0:
counter[char] += 1
elif counter[char] == 0:
break
elif counter[char] > 0:
raise Exception("Impossible situation: This should never happen")
il += 1
# one solution here
if res is not None:
res = s[il:i_char+1] if len(res) > (i_char-il+1) else res
else:
res = s[il:i_char+1]
if len(res) == 1:
return res
# if counter[]
counter[char] += 1 # This should never crash
required_char_countdown +=1
il += 1
return res if res is not None else ""
s = Solution()
assert s("ADOBECODEBANC", "ABC") == "BANC", s("ADOBECODEBANC", "ABC") if s("ADOBECODEBANC", "ABC") else "EMPTY"