All coding questions

Minimum Window Substring

hard
Blind 75NeetCode 150stringssliding-windowhashing

Problem

Given a string s and a pattern t, find the shortest contiguous substring of s that contains every character of t including duplicates. If none exists, return an empty string.

Examples

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
The shortest window covering A, B, and C.
Input: s = "a", t = "aa"
Output: ""
s lacks a second a.

Constraints

  • 1 <= s.length, t.length <= 10^5
  • Strings contain upper and lower case English letters
Hints(tap to reveal)
  • 1. Track how many required characters are still missing.
  • 2. Expand to satisfy, then contract to minimize.
Optimal approach(spoiler)
  1. Count the required character frequencies from t.
  2. Expand the right edge, decrementing needs and a missing counter.
  3. Once all needs are met, contract the left edge while still valid.
  4. Record the smallest valid window seen.
  5. O(n) time, O(alphabet) space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor