Minimum Window Substring — LeetCode 76 Python Solution

HardHash TableStringSliding Window
Problem
#76
Reading time
3 min

The problem

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

Example

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

Python solution

Python
class Solution:
    def minWindow(self, s: str, t: str) -> str:
        need = Counter(t)
        window = Counter()
        cnt = l = 0
        k, mi = -1, inf
        for r, c in enumerate(s):
            window[c] += 1
            if need[c] >= window[c]:
                cnt += 1
            while cnt == len(t):
                if r - l + 1 < mi:
                    mi = r - l + 1
                    k = l
                if need[s[l]] >= window[s[l]]:
                    cnt -= 1
                window[s[l]] -= 1
                l += 1
        return "" if k < 0 else s[k : k + mi]

Complexity

MeasureComplexity
TimeO(m + n)
SpaceO(|\Sigma|) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 76. Minimum Window Substring is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 76. Minimum Window Substring?
LeetCode 76. Minimum Window Substring is rated Hard on LeetCode.
What is the time complexity of LeetCode 76. Minimum Window Substring?
The Python solution on this page runs in O(m + n).
What is the space complexity of LeetCode 76. Minimum Window Substring?
The Python solution on this page uses O(|\Sigma|) auxiliary space.
What topics does LeetCode 76. Minimum Window Substring cover?
LeetCode 76. Minimum Window Substring is tagged Hash Table, String and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview