☰ All problems

Minimum Window Substring

A monitoring tool records events as a string s, one letter per event, where uppercase and lowercase letters are different event types. An engineer wants the shortest stretch of the log that contains every event listed in t, counting repeats: if t lists an event type twice, the stretch must contain it at least twice.

Return that shortest contiguous stretch of s. If no stretch qualifies, return the empty string "". Whenever an answer exists, the tests make sure the shortest stretch is unique.

Example 1
Input: s = "ZAQBXCBAY", t = "ABC"
Output: "CBA"

Explanation: "AQBXC" also contains A, B and C, but the three-letter stretch "CBA" is shorter.

Example 2
Input: s = "baacab", t = "aab"
Output: "baa"

Explanation: t needs two as and one b. "baa" is the only three-letter stretch that has them all.

Example 3
Input: s = "Abc", t = "a"
Output: ""

Explanation: Event types are case-sensitive: s contains A but no a.

Constraints

  • s and t are each between 1 and 10^5 characters long.
  • Both strings contain only English letters, uppercase or lowercase.

Follow-up: Checking every start and end position is easy but slow. Can you get the running time down to one pass over s plus one pass over t?

💡 Hint 1

Count what t needs. A window of s is valid when it has at least that many of every character.

💡 Hint 2

Grow a window to the right until it is valid, then shrink it from the left for as long as it stays valid, recording the shortest valid window.

💡 Hint 3

Track a single number, how many required characters are still missing, so validity is an O(1) check instead of comparing all counts.

/**
 * @param {string} s
 * @param {string} t
 * @return {string}
 */
function minWindow(s, t) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc