☰ All problems

22. Minimum Window Substring

Given two strings s and t, return the shortest substring of s that contains every character of t, including repeats: if t has a letter twice, the window must contain it at least twice. Letters are case-sensitive.

If no such substring exists, return the empty string "". The tests guarantee that whenever a window exists, the shortest one is unique.

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

Explanation: "AYBZC" and "BZCA" also contain A, B and C, but "CAB" is the shortest.

Example 2
Input: s = "a", t = "a"
Output: "a"
Example 3
Input: s = "a", t = "aa"
Output: ""

Explanation: t needs two as but s has only one.

Constraints

  • 1 <= s.length, t.length <= 10^5
  • s and t consist of uppercase and lowercase English letters

Follow-up: Can you find the answer in O(|s| + |t|) time?

💡 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