Question
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string “”.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Hide Tags Hash Table Two Pointers String
Hide Similar Problems (H) Substring with Concatenation of All Words (M) Minimum Size Subarray Sum (H) Sliding Window Maximum
Solution
Get idea from here, here2, here3
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
dictn = {}
for elem in t:
if elem in dictn:
dictn[elem] += 1
else:
dictn[elem] = 1
cnt, l, minl, minsize = 0, 0, 0, len(s)+1
for r in range(len(s)):
if s[r] in dictn:
dictn[s[r]] -= 1
if dictn[s[r]]>=0:
cnt += 1
while cnt==len(t):
if r-l+1<minsize:
minl = l
minsize = r-l+1
if s[l] in dictn:
dictn[s[l]] += 1
if dictn[s[l]]>0:
cnt -= 1
l += 1
if minsize>len(s):
return ''
return s[minl:minl+minsize]