Sliding Window · Variable size

Minimum Window Visualizer

What is Minimum Window

Return the shortest substring of s that contains every character of t, including duplicates. If several windows share that length, return the leftmost. If none exists, the practice output is a blank line. This picture shows none.

ADOBECODEBANC
ABC
BANC

Approach

Check every substringTesting every pair of ends against the required counts is too slow on a long string.
Expand until covered, then shrinkMove the right edge until the window satisfies the counts. Then move the left edge while it still does, and remember the shortest window.

Interactive solution

The window and the need count for each required letter
count what t still needs
expand the right edge
while the window covers t:
remember it when it is shorter
drop the left character
return the best window
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.

Complexity

PieceCostWhy
TimeO(n)Each character of s enters and leaves once.
MemoryO(1)The count tables are bounded by the alphabet, and t is short.

Implementation

def min_window(s, t):
    need = {}
    for ch in t:
        need[ch] = need.get(ch, 0) + 1
    have = 0
    required = len(need)
    window, l, best = {}, 0, None
    for r, ch in enumerate(s):
        window[ch] = window.get(ch, 0) + 1
        if ch in need and window[ch] == need[ch]:
            have += 1
        while have == required and l <= r:
            if best is None or r - l + 1 < best[1] - best[0] + 1:
                best = (l, r)
            left = s[l]
            window[left] -= 1
            if left in need and window[left] < need[left]:
                have -= 1
            l += 1
    if best is None:
        return ""
    return s[best[0]:best[1] + 1]