-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04_MinimumWindowSubstring.py
More file actions
36 lines (27 loc) · 1.09 KB
/
04_MinimumWindowSubstring.py
File metadata and controls
36 lines (27 loc) · 1.09 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
# Question link - https://leetcode.com/problems/minimum-window-substring/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def minWindow(self, s: str, t: str) -> str:
if t == "":
return ""
countT, window = {}, {}
for c in t:
countT[c] = 1 + countT.get(c, 0)
have, need = 0, len(countT)
res, resLen = [-1, -1], float("infinity")
l = 0
for r in range(len(s)):
window[s[r]] = 1 + window.get(s[r], 0)
if s[r] in countT and window[s[r]] == countT[s[r]]:
have += 1
while have == need:
# Update result if a smaller window is found
if (r - l + 1) < resLen:
res = [l, r]
resLen = (r - l + 1)
# Remove the leftmost character from window
window[s[l]] -= 1
if s[l] in countT and window[s[l]] < countT[s[l]]:
have -= 1
l += 1
l, r = res
return s[l:r+1] if resLen != float("infinity") else ""