class Solution:
def minWindow(self, s: str, t: str) -> str:
# time O(S+T) space O(T)
# step1: initialize l, minL, minLen, cnt_s, cnt_t. where cnt_s record valid ch in s for t.
# step2: record freq for each char in t
d = {}
for c in t:
d[c] = d.get(c,0)+1
l = minL = 0
size_s = len(s)
min_len = len(s) +1
cnt_t = len(t)
cnt_s = 0
# step3: loop through s using r as pointer, if found s[r] in d, update d and increment cnt_s if s[r] in d >= 0
for r in range(size_s):
if s[r] in d:
d[s[r]] -= 1
if d[s[r]] >= 0:
cnt_s += 1
# step3.1: when cnt_s == cnt_t, update minL and min_len
while cnt_s == cnt_t:
if r-l+1 < min_len:
minL = l
min_len = r- l + 1
# step3.2: check if s[l] in d, if yes, update d, check if s[l] valid in t by checking if d[s[l]]> 0, note not >= 0 . decrement cnt_s
if s[l] in d:
d[s[l]] += 1
if d[s[l]] > 0:
cnt_s -= 1
# step3.3 left ptr move ++
l += 1
# step4: check if min_len > len(s)
if min_len > len(s):
return ""
else:
return s[minL:minL+min_len]