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.

Source: leetcode | Difficulty: MEDIUM_HARD
Tags: String algorithms

Data structures

Amortized analysis

Starter code: class Solution:
    def minWindow(self, s: str, t: str) -> str:
        

Solutions:
class Solution:

	def minWindow(self, s, t):
		left = -1
		right = 0
		result = ''
		totalMatch = 0
		d = {}
		for c in t:
			d[c] = d.get(c, 0) + 1
		for right in range(len(s)):
			c = s[right]
			d[c] = d.get(c, 0) - 1
			if d[c] >= 0:
				totalMatch += 1
				if totalMatch == len(t):
					totalMatch -= 1
					left += 1
					while d[s[left]] < 0:
						d[s[left]] += 1
						left += 1
					d[s[left]] += 1
					if result == '' or len(result) > right - left:
						result = s[left:right + 1]
		return result


class Solution:

	def minWindow(self, s, t):
		table = {}
		for c in t:
			table[c] = table[c] + 1 if c in table else 1
		(start, end, count) = (0, 0, len(t))
		(min_start, min_end) = (None, None)
		for i in range(len(s)):
			if s[i] in table:
				if table[s[i]] > 0:
					count -= 1
				table[s[i]] -= 1
			if count == 0:
				while count == 0:
					if s[start] in table:
						if table[s[start]] >= 0:
							count += 1
							if min_start == None or i - start < min_end - min_start:
								(min_start, min_end) = (start, i)
						table[s[start]] += 1
					start += 1
		if min_start == None:
			return ''
		else:
			return s[min_start:min_end + 1]


class Solution:

	def minWindow(self, s, t):
		if len(t) > len(s):
			return ''
		dic = {}
		for i in t:
			if i in dic:
				dic[i] += 1
			else:
				dic[i] = 1
		counter = len(dic)
		start = end = 0
		minl = len(s) + 1
		res = ''
		while end < len(s):
			j = s[end]
			if j in dic:
				dic[j] -= 1
				if dic[j] == 0:
					counter -= 1
			end += 1
			while counter == 0:
				i = s[start]
				if i in dic:
					dic[i] += 1
					if dic[i] > 0:
						counter += 1
					if end - start < minl:
						minl = end - start
						res = s[start:end]
				start += 1
		return res