1
+ def min_window (s , t ):
2
+ # empty string scenario
3
+ if t == "" :
4
+ return ""
5
+
6
+ # creating the two hash maps
7
+ req_count = {}
8
+ window = {}
9
+
10
+ # populating req_count hash map
11
+ for c in t :
12
+ req_count [c ] = 1 + req_count .get (c , 0 )
13
+
14
+ # populating window hash map
15
+ for c in t :
16
+ window [c ] = 0
17
+
18
+ # setting up the conditional variables
19
+ current , required = 0 , len (req_count )
20
+
21
+ # setting up a variable containing the result's starting and ending point
22
+ # with default values and a length variable
23
+ res , res_len = [- 1 , - 1 ], float ("infinity" )
24
+
25
+ # setting up the sliding window pointers
26
+ left = 0
27
+ for right in range (len (s )):
28
+ c = s [right ]
29
+
30
+ # if the current character also occurs in t, update its frequency in window hash map
31
+ if c in t :
32
+ window [c ] = 1 + window .get (c , 0 )
33
+
34
+ # updating the current variable
35
+ if c in req_count and window [c ] == req_count [c ]:
36
+ current += 1
37
+
38
+ # adjusting the sliding window
39
+ while current == required :
40
+ # update our result
41
+ if (right - left + 1 ) < res_len :
42
+ res = [left , right ]
43
+ res_len = (right - left + 1 )
44
+
45
+ # pop from the left of our window
46
+ if s [left ] in t :
47
+ window [s [left ]] -= 1
48
+
49
+ # if the popped character was among the required characters and
50
+ # removing it has reduced its frequency below its frequency in t, decrement current
51
+ if s [left ] in req_count and window [s [left ]] < req_count [s [left ]]:
52
+ current -= 1
53
+ left += 1
54
+ left , right = res
55
+
56
+ # return the minimum window substring
57
+ return s [left :right + 1 ] if res_len != float ("infinity" ) else ""
58
+
59
+ # driver Code
60
+ def main ():
61
+ s = ["PATTERN" , "LIFE" , "ABRACADABRA" , "STRIKER" , "DFFDFDFVD" ]
62
+ t = ["TN" , "I" , "ABC" , "RK" , "VDD" ]
63
+ for i in range (len (s )):
64
+ print (i + 1 , ".\t s: " , s [i ], "\n \t t: " , t [i ], "\n \t The minimum substring containing " , \
65
+ t [i ], " is: " , min_window (s [i ], t [i ]), sep = "" )
66
+ print ("-" * 100 )
67
+
68
+ if __name__ == '__main__' :
69
+ main ()
0 commit comments