Leetcode: 76. Minimum Window Substring

Problem Statement

from collections import defaultdict


class Solution:
    def minWindow(self, s: str, t: str) -> str:
        R = len(set(t))
        N = len(s)
        required = defaultdict(int)
        for c in t:
            required[c] += 1

        freq = defaultdict(int)
        cnt_ok = 0

        start = 0
        valid = False

        ans = None
        for end, c in enumerate(s):
            if not valid and freq[c] == required[c] - 1:
                cnt_ok += 1
                valid = cnt_ok == R

            freq[c] += 1
            while start < N and freq[s[start]] > required[s[start]]:
                freq[s[start]] -= 1
                start += 1

            if valid and (ans is None or (ans[1] - ans[0] + 1) > (end - start + 1)):
                ans = (start, end)

        return s[ans[0] : ans[1] + 1] if ans else ""


assert Solution().minWindow("ADOBECODEBANC", "ABC") == "BANC"
assert Solution().minWindow("a", "a") == "a"