Skip to problem
←

Minimum Window Substring

Hard 0 attempts

Given two strings s and t, locate the shortest contiguous substring of s that includes every character from t, matching duplicate counts as well. If no such substring is present, return an empty string instead.

Whenever a valid window exists, there's exactly one smallest one that satisfies the condition.

Matching is case-sensitive: "a" and "A" differ. Characters may occur in any order inside the window, and unrelated characters may be included. Duplicate requirements must be satisfied: for t = "AAB", one A is insufficient. Return the substring itself, not its length.

Function contract

Implement minWindow(s, t). Receive two nonempty English-letter strings. Character comparisons are case-sensitive.

Output: Return the shortest contiguous substring of s containing every character of t with at least its required count, or "" if impossible.

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
  • s and t consist of uppercase and lowercase English letters
  • If a covering window exists, the minimum-length window is unique

Sliding window with two pointers. Build a frequency map for t. Expand the right pointer until the window satisfies all requirements, then shrink from the left to find the tightest valid window. Track how many distinct characters are fully satisfied to avoid recounting the entire map each step.

javascript
function minWindow(s, t) {
  if (t.length > s.length) return '';

  const need = new Map();
  for (const ch of t) need.set(ch, (need.get(ch) || 0) + 1);

  let have = 0;
  const required = need.size;
  const window = new Map();
  let minLen = Infinity;
  let minStart = 0;
  let left = 0;

  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    window.set(ch, (window.get(ch) || 0) + 1);

    if (need.has(ch) && window.get(ch) === need.get(ch)) {
      have++;
    }

    while (have === required) {
      if (right - left + 1 < minLen) {
        minLen = right - left + 1;
        minStart = left;
      }
      const leftCh = s[left];
      window.set(leftCh, window.get(leftCh) - 1);
      if (need.has(leftCh) && window.get(leftCh) < need.get(leftCh)) {
        have--;
      }
      left++;
    }
  }

  return minLen === Infinity ? '' : s.substring(minStart, minStart + minLen);
}

Time: O(|s| + |t|) — each pointer traverses the string at most once. Space: O(1) auxiliary space for maps containing at most 52 distinct English letters, plus O(L) for the returned substring of length L.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript