[Leetcode] 0076. Minimum Window Substring

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link

Table of contents

Hard


Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".

The testcases will be generated such that the answer is unique.

 

Example 1:

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.

Example 2:

Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.

Example 3:

Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return an empty string.

 

Constraints:

  • m == s.length
  • n == t.length
  • 1 <= m, n <= 10 5
  • s and t consist of uppercase and lowercase English letters.

 

Follow up: Could you find an algorithm that runs in O(m + n) time?

Python

				
					# time complexity: O(len(s) + len(t)) # space complexity: O(len(s) + len(t)) from collections import Counter, defaultdict class Solution: def minWindow(self, s: str, t: str) -> str: reqCount = defaultdict(int) window = defaultdict(int) result = [-1, -1] resultLen = float('inf') current = 0 for char in t: reqCount[char] + = 1 required = len(reqCount) left = 0 for right in range(len(s)): char = s[right] if char in reqCount: window[char] += 1 if window[char] == reqCount[char ]: current += 1 while current == required: if (right - left + 1) < resultLen: resultLen = right - left + 1 result = [left, right] leftChar = s[left] if leftChar in window: window[ leftChar] -= 1 if window[leftChar] < reqCount[leftChar]: current -= 1 left += 1 return s[result[0]:result[1] + 1] if resultLen != float('inf') else "" S = "ADOBECODEBANC" T = "ABC" print(Solution().minWindow(S, T))
				
			
en_USEnglish