Skip to content

Commit 0e93ace

Browse files
authored
(leetcode)Solution for minimum window substring
1 parent 58ae834 commit 0e93ace

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
def minWindow(self, s, t):
2+
"""
3+
:type s: str
4+
:type t: str
5+
:rtype: str
6+
"""
7+
8+
if not t or not s:
9+
return ""
10+
11+
# Dictionary which keeps a count of all the unique characters in t.
12+
dict_t = Counter(t)
13+
14+
# Number of unique characters in t, which need to be present in the desired window.
15+
required = len(dict_t)
16+
17+
# left and right pointer
18+
l, r = 0, 0
19+
20+
# formed is used to keep track of how many unique characters in t are present in the current window in its desired frequency.
21+
# e.g. if t is "AABC" then the window must have two A's, one B and one C. Thus formed would be = 3 when all these conditions are met.
22+
formed = 0
23+
24+
# Dictionary which keeps a count of all the unique characters in the current window.
25+
window_counts = {}
26+
27+
# ans tuple of the form (window length, left, right)
28+
ans = float("inf"), None, None
29+
30+
while r < len(s):
31+
32+
# Add one character from the right to the window
33+
character = s[r]
34+
window_counts[character] = window_counts.get(character, 0) + 1
35+
36+
# If the frequency of the current character added equals to the desired count in t then increment the formed count by 1.
37+
if character in dict_t and window_counts[character] == dict_t[character]:
38+
formed += 1
39+
40+
# Try and contract the window till the point where it ceases to be 'desirable'.
41+
while l <= r and formed == required:
42+
character = s[l]
43+
44+
# Save the smallest window until now.
45+
if r - l + 1 < ans[0]:
46+
ans = (r - l + 1, l, r)
47+
48+
# The character at the position pointed by the `left` pointer is no longer a part of the window.
49+
window_counts[character] -= 1
50+
if character in dict_t and window_counts[character] < dict_t[character]:
51+
formed -= 1

0 commit comments

Comments
 (0)