Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

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).

Example:

Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note:

If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

My code:

class Solution:
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        left, right, res_l, res_r, min_len = 0, 0, 0, 0, float("inf")
        count_map = collections.defaultdict(int)
        for char in t: count_map[char] += 1
        while right <= len(s):
            if all(map(lambda i: True if i <= 0 else False, count_map.values())):
                if (right - left) < min_len:
                    min_len = right - left
                    res_l, res_r = left, right
                if s[left] in count_map: count_map[s[left]] += 1
                left += 1
            else:
                if right == len(s): break
                if s[right] in count_map: count_map[s[right]] -= 1
                right += 1
        return s[res_l:res_r]
                
                
                

Solution: https://leetcode.com/problems/minimum-window-substring/