Practice · Sliding window · 4 of 4

Smallest Window Holding Every Letter

You are given two strings s and t. Return the shortest substring of s that contains every character of t, repeats included: if t has two as, the substring needs at least two as. The characters can come in any order, and the substring may hold other characters as well.

If no substring of s works, return the empty string "". If several shortest substrings work, return the one that starts first (the leftmost).

Example 1

Input
s = "XAYBZACB", t = "ABC"
Output
"ACB"
ACB (positions 5 to 7) holds an A, a B and a C, and no shorter stretch does.

Example 2

Input
s = "baab", t = "ab"
Output
"ba"
ba and ab both work and are equally short; ba starts first.

Example 3

Input
s = "a", t = "aa"
Output
""
t needs two as, but s has only one.

Constraints

  • s and t each hold 1 to 10⁵ characters.
  • Both contain only English letters; upper and lower case are different characters.