LC076 - Minimum Window Substring
Problem
Example
Solution
def minWindow(self, s: str, t: str) -> str:
if t == "":
return ""
req = {}
cur = {}
# Can use collections.Counter for this
for char in t:
if char in req:
tmp = req[char]
req[char] = tmp + 1
else:
req[char] = 1
reqN = len(req)
curN = 0
res = [0,-1]
resLen = math.inf
left = 0
for right in range(len(s)):
char = s[right]
if char in cur:
tmp = cur[char]
cur[char] = tmp + 1
else:
cur[char] = 1
if char in req and cur[char] == req[char]:
curN += 1
# if window is smaller, then update smallest window size
while reqN == curN:
if (right - left + 1) < resLen:
res = [left, right]
resLen = (right - left + 1)
# remove the leftmost char of current window
cur[s[left]] -= 1
if s[left] in req and cur[s[left]] < req[s[left]]:
curN -= 1
left += 1
left, right = res
if resLen != math.inf:
return s[left:right+1]
else:
return ""Last updated