Minimum Window Substring

Hard

Topics
Hash TableStringSliding Window

Given two strings s and t, return the smallest substring of s that contains every character of t (including duplicates). If there is no such window, return the empty string "". When several windows share the minimum length, return the one with the smallest starting index.

Example 1

A0D1O2B3E4C5O6D7E8B9A10N11C12BANC
The braced window contains every character of ABC, counting duplicates, and is the shortest that does — BANC.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"

Example 2

a0a
Input:  s = "a", t = "a"
Output: "a"

Example 3

a0a
Input:  s = "a", t = "aa"
Output: ""

Constraints

  • 1 <= s.length <= 16
  • 1 <= t.length <= 6
  • s and t consist of lowercase and uppercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The brute force is to take every substring of s, check whether it covers t, and keep the shortest that does. There are O(n^2) substrings and each check costs O(n), so that is O(n^3) — fine to state, useless to run.

The first real improvement is noticing that the check is incremental. If you extend a window one character to the right, you do not need to recount it; you adjust one tally. That alone drops the check to O(1) amortised.

The second is the observation that makes this a window rather than a search. Suppose a window [left, right] already covers t. Then every wider window starting at the same left also covers t and is longer, so it cannot be the answer. The only useful move is to shrink from the left. And once shrinking breaks coverage, extending left further is hopeless too — you must grow right again. So each pointer only ever moves forward, and the whole scan is linear.

The bookkeeping trick that keeps it O(1) per step is to track a single number, missing: how many characters of t are still unmatched, counting multiplicity. Coverage is then not a map comparison but the test missing == 0.

The one subtlety is that a window may hold surplus copies of a character. Decrement missing only when the copy you just consumed was actually needed — that is, when the stored requirement for it was still positive.

Approach

  1. Build need, a count per character of t. Set missing = len(t), which counts duplicates: t = "AABC" needs two A's, not one.
  2. Advance right across s. For each character, decrement its entry in need. If that entry was positive before the decrement, the copy was genuinely needed, so decrement missing too. A surplus copy drives the entry negative and leaves missing alone, which is exactly how the surplus is remembered.
  3. While missing == 0 the window is valid. Record it if it beats the best so far, then shrink: increment need for the character at left, and if that entry becomes positive the character was load-bearing, so missing goes back up and the window stops being valid.
  4. Return the best window, or the empty string if none was ever valid.

A negative entry in need means surplus, zero means exactly met, positive means still owed. That sign convention is doing the work that a second map would otherwise do.

Dry Run

s = "ADOBECODEBANC", t = "ABC". So need = {A:1, B:1, C:1} and missing = 3.

right  ch   need[ch]  missing
  0    A       0         2    needed
  1    D      -1         2    surplus
  2    O      -1         2    surplus
  3    B       0         1    needed
  4    E      -1         1    surplus
  5    C       0         0    needed
       -> valid [0..5] "ADOBEC" len 6   BEST
       -> drop A at 0: need[A]=1 POSITIVE, missing=1, invalid

  6    O      -2         1
  7    D      -2         1
  8    E      -2         1
  9    B      -1         1    surplus B, missing unchanged
 10    A       0         0    needed
       -> valid [1..10] "DOBECODEBA" len 10   not better
       -> drop D: -1 surplus, still valid
       -> valid [2..10] "OBECODEBA"  len  9   not better
       -> drop O: -1 surplus, still valid
       -> valid [3..10] "BECODEBA"   len  8   not better
       -> drop B:  0 surplus, still valid
       -> valid [4..10] "ECODEBA"    len  7   not better
       -> drop E: -1 surplus, still valid
       -> valid [5..10] "CODEBA"     len  6   ties 6, best unchanged
       -> drop C at 5: need[C]=1 POSITIVE, missing=1, invalid

 11    N      -1         1
 12    C       0         0    needed
       -> valid [6..12] "ODEBANC"    len  7   not better
       -> drop O:  0 surplus, still valid
       -> valid [7..12] "DEBANC"     len  6   ties 6, best unchanged
       -> drop D:  0 surplus, still valid
       -> valid [8..12] "EBANC"      len  5   BEST
       -> drop E:  0 surplus, still valid
       -> valid [9..12] "BANC"       len  4   BEST
       -> drop B at 9: need[B]=1 POSITIVE, missing=1, invalid

Answer "BANC". Two things the trace makes visible. The long shrink after right=10 walks left from 1 to 6 in one burst, and the answer improves twice in the final shrink — through "EBANC" before reaching "BANC" — which is why the record step has to sit inside the shrink loop rather than after it. And left never moves backwards anywhere in the run, which is the property that buys the linear bound.

Complexity

  • Time — O(|s| + |t|): building need is O(|t|). Then right advances |s| times and left advances at most |s| times, and neither ever retreats, so the scan is O(|s|) even though it is written as a loop inside a loop. Each step is O(1) because coverage is the integer test missing == 0 rather than a map comparison. Compare the O(n^3) enumerate-every-substring opener.
  • Space — O(|s| + |t|): the need map holds at most one entry per distinct character of t, plus the surplus entries created by characters of s — so O(|t|) for what is owed and O(|s|) in the worst case for what is in surplus. With the problem's constraint of uppercase and lowercase letters only this is bounded by the 52-letter alphabet, i.e. O(1), and saying so is the better answer if you have established the alphabet is fixed.

Common Pitfalls

  • Setting missing = len(need) instead of len(t). That ignores duplicates, so t = "AABC" would be satisfied by a window holding a single A.
  • Decrementing missing on every matching character rather than only when the requirement was still positive. A window with three A's where two are needed would then report coverage one character early.
  • Shrinking with if rather than while. After a window becomes valid there may be several removable characters at the left, and stopping after one leaves a window that is valid but not minimal.
  • Recording the answer after shrinking instead of before. The window is minimal at the moment just before it stops being valid, so measure it inside the shrink loop.
  • Storing the best substring itself on every improvement. Keep the start index and length and slice once at the end, or the copying turns an O(n) scan into O(n^2) in the worst case.
  • Returning some sentinel rather than "" when no window covers t, including the case |t| > |s|.

Full Solution — all languages

class Solution:
    def minWindow(self, s, t):
        if not t:
            return ""
        need = {}
        for c in t:
            need[c] = need.get(c, 0) + 1
        required = len(need)
        have = {}
        formed = 0
        l = 0
        best_len = float('inf')
        best_l = 0
        for r in range(len(s)):
            c = s[r]
            if c in need:
                have[c] = have.get(c, 0) + 1
                if have[c] == need[c]:
                    formed += 1
            while formed == required:
                if r - l + 1 < best_len:
                    best_len = r - l + 1
                    best_l = l
                lc = s[l]
                if lc in need:
                    have[lc] -= 1
                    if have[lc] < need[lc]:
                        formed -= 1
                l += 1
        return "" if best_len == float('inf') else s[best_l:best_l + best_len]
SensAI
Beta
Tap the mic to stop voice mode