Skip to content
Problem 76 · LeetCode 76(opens in a new tab)

Minimum Window Substring

HardHash tables

You get two strings, s and t. Find the shortest stretch of consecutive letters in s that holds every letter of t, counting repeats: if t has two as, the stretch needs at least two as.

Return that stretch. If no stretch of s holds all of t, return the empty string. Upper and lower case letters are different. When an answer exists, only one stretch has the shortest length.

Example 1

Input:  s = "CBDACB", t = "ABC"
Output: "ACB"
Why:    CBDA, BDAC and DACB also cover t, but ACB is shorter
2 more examples and the constraints

Example 2

Input:  s = "q", t = "q"
Output: "q"
Why:    all of s is the only window

Example 3

Input:  s = "b", t = "bb"
Output: ""
Why:    t needs two b, s has only one

Constraints

  • 1 ≤ length of s, length of t ≤ 100,000
  • s and t contain only English letters, upper or lower case

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every start, grow until coveredO(m²)
  2. Sliding windowO(m + n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 lettersVerdict
Every start, grow until coveredO(m²)
Mention it, then move on
Sliding windowO(m + n)
Best; each letter in and out once

m = length of s, n = length of t, k = distinct letters in t.

Edge cases to test

  • t longer than s. No window can hold it: s = "ab", t = "abc" gives "".
  • Repeated letters in t. t = "AA" needs two A in the window; one is not enough.
  • Case matters. s = "aA", t = "A" gives "A", not "aA".
  • Whole string. Sometimes only all of s covers t; s = "abc", t = "cba" gives "abc".
  • No match at all. A letter of t that never appears in s means the answer is "".

Common mistakes

  • Checking coverage by comparing whole count tables on every step, which turns O(m) into O(m·k).
  • Lowering missing for every matching letter, even extra copies, so the window looks covered too early.
  • Recording the window after shrinking past the point where it still covers t.

How to talk through it

  1. 1Clarify. Do repeats in t count? Is case significant? What do I return when nothing works?
  2. 2Give the brute force. Every start, grow until covered: O(m²), and say what work it repeats.
  3. 3Name the window. Covering t only gets easier as the window grows, so grow on the right and shrink on the left.
  4. 4Code the counts. One map for what is still needed and one number, missing, so each move is O(1).
  5. 5Test out loud. Run t longer than s, a repeated letter in t, and a case-sensitive pair.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?