#76
Hard
Sliding Window

Minimum Window Substring

Find the smallest substring that contains all characters of t.

Find the smallest substring in s that contains all characters of t, including multiplicity. The challenge is not finding a valid window once, but shrinking it without losing required coverage.

StringSliding Window

Pattern fit

This is the classic coverage window: expand until every required character is satisfied, then shrink as much as possible while staying valid.

Key observation

The key state is not distinct count alone but how many required character frequencies have been fully satisfied.

Target complexity

O(n) / O(k)

How to break down the solution cleanly

1

Build a frequency map for t so you know how many of each character are required.

2

Expand the right pointer and decrease the need count for that character.

3

When all required characters are satisfied, try shrinking from the left while staying valid.

4

Each time the window is valid, compare it against the best answer so far.

Walk through one example

1

Example: s = "ADOBECODEBANC", t = "ABC".

2

The first valid window is "ADOBEC", but it is not minimal.

3

Continue expanding and shrinking until the window "BANC" is found.

4

At that point no shorter valid window exists, so answer is "BANC".

Reference implementation

Python
from collections import Counter

def minWindow(s: str, t: str) -> str:
    need = Counter(t)
    missing = len(t)
    left = 0
    best_start = 0
    best_len = float("inf")

    for right, char in enumerate(s):
        if need[char] > 0:
            missing -= 1
        need[char] -= 1

        while missing == 0:
            if right - left + 1 < best_len:
                best_start = left
                best_len = right - left + 1

            left_char = s[left]
            need[left_char] += 1
            if need[left_char] > 0:
                missing += 1
            left += 1

    if best_len == float("inf"):
        return ""

    return s[best_start:best_start + best_len]

Common pitfalls

warning

Treating required coverage as set membership instead of frequency satisfaction.

warning

Shrinking after the window already became invalid.

Common follow-ups

What changes if you need the number of valid windows instead of the minimum window?

How do you know when to decrement the matched counter?

Continue with related problems

Build repeatable depth inside the Sliding Window cluster before moving on.

view_weekBack to the pattern page
LeetCode 76. Minimum Window Substring Guide | Interview AiBox