Minimum Window Substring

HardSliding window

Given two strings s and t, return the shortest substring of s, a run of consecutive characters, that contains every character of t, each at least as many times as it appears in t.

Upper and lowercase letters are different characters. If no substring of s works, return the empty string "". If several shortest substrings tie, return any of them.

Examples

Example 1
Input:  s = "XAYBZCAB", t = "ABC"
Output: "CAB"

CAB holds an A, a B and a C, and no shorter piece of s does.

Example 2
Input:  s = "aab", t = "aaa"
Output: ""

s has only two a’s, and t needs three.

Constraints

  • 1 ≤ s.length, t.length ≤ 10⁵
  • s and t use upper and lowercase English letters only.

Stuck?

Hint 1

Grow a window to the right until it holds everything t needs, then shrink it from the left for as long as it still does.

Hint 2

Count what t needs in a Map, and keep a number of characters still missing, so checking the window is O(1) instead of comparing every count.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur