Skip to content

Commit e6dba98

Browse files
committed
- Minimum Window Substring #285
1 parent a225135 commit e6dba98

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

minimum-window-substring/ayosecu.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from collections import Counter, defaultdict
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n), n = len(s)
6+
- Space Complexity: O(m), m = len(t)
7+
"""
8+
def minWindow(self, s: str, t: str) -> str:
9+
need = Counter(t)
10+
need_len = len(need)
11+
win_dic = defaultdict(int)
12+
cnt = 0
13+
min_range, min_len = [-1, -1], float("inf")
14+
15+
l = 0
16+
for r in range(len(s)):
17+
c = s[r]
18+
win_dic[c] += 1
19+
20+
if c in need and win_dic[c] == need[c]:
21+
cnt += 1
22+
23+
while cnt == need_len:
24+
# Update min range
25+
check_len = r - l + 1
26+
if check_len < min_len:
27+
min_range = [l, r]
28+
min_len = check_len
29+
30+
# Move left pointer
31+
win_dic[s[l]] -= 1
32+
if s[l] in need and win_dic[s[l]] < need[s[l]]:
33+
cnt -= 1
34+
l += 1
35+
36+
return s[min_range[0]:min_range[1]+1] if min_len != float("inf") else ""
37+
38+
tc = [
39+
("ADOBECODEBANC", "ABC", "BANC"),
40+
("a", "a", "a"),
41+
("a", "aa", "")
42+
]
43+
44+
sol = Solution()
45+
for i, (s, t, e) in enumerate(tc, 1):
46+
r = sol.minWindow(s, t)
47+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)