Coding problem · Hard · Sliding Window

Minimum Window Substring

Hard Algorithms & data structures Seen at Meta, Amazon, Airbnb, LinkedIn

Given strings s and t, return the minimum window substring of s that contains every character of t (including duplicates). If there is no such window, return "". The answer is unique.

Example 1

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"

Example 2

Input: s = "a", t = "aa"
Output: ""

Constraints

  • 1 <= s.length, t.length <= 10^5

Hints

Hint 1

Expand right until the window covers t, then shrink left while it still covers it.

Hint 2

Track how many required characters are currently satisfied instead of re-checking the whole map.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(|s| + |t|) · Space O(alphabet)

Count what t needs. Move right forward, decrementing needs; when a need reaches zero, one more character is satisfied. Once all are satisfied, record the window and move left forward, giving characters back, until the window stops being valid. Every index enters and leaves the window once: O(|s| + |t|).

Reference solution

function minWindow(s, t) {
  const need = new Map();
  for (const c of t) need.set(c, (need.get(c) ?? 0) + 1);
  let missing = need.size, left = 0, best = [0, Infinity];
  for (let right = 0; right < s.length; right++) {
    const c = s[right];
    if (need.has(c)) {
      need.set(c, need.get(c) - 1);
      if (need.get(c) === 0) missing--;
    }
    while (missing === 0) {
      if (right - left < best[1] - best[0]) best = [left, right];
      const d = s[left++];
      if (need.has(d)) {
        need.set(d, need.get(d) + 1);
        if (need.get(d) > 0) missing++;
      }
    }
  }
  return best[1] === Infinity ? "" : s.slice(best[0], best[1] + 1);
}