codejump
HardPythonJavaScriptTypeScript

Sliding Window — Minimum Window Substring

AlgorithmsSliding WindowStringsHash Table

Return the shortest substring of s that contains every character of
t, with multiplicity (if t has two 'a', the window needs two).
Return '' when no such window exists. If several windows share the minimum
length, return the leftmost one.

Expand the right edge until the window covers t, then shrink the left edge
as long as it still does, recording each valid window. Track how many
characters are still missing instead of re-checking all counts at every step,
and the whole thing is O(|s| + |t|).

Examples

solve('ADOBECODEBANC', 'ABC')  → 'BANC'
solve('a', 'a')                → 'a'
solve('a', 'aa')               → ''    // t needs two 'a'

Constraints

  • 1 <= s.length, t.length <= 100000
  • Comparisons are case-sensitive: 'a' and 'A' are different characters.

Sample tests

Test #1The classic example
Input: ["ADOBECODEBANC","ABC"]
Output: "BANC"
Test #2The whole string
Input: ["a","a"]
Output: "a"
Test #3t needs two copies of the same character
Input: ["a","aa"]
Output: ""