CodingNodes / Sliding Window / Minimum Window Substring System design Space play · ←→ step · R restart

Problem

You are given two strings s and t. Find the shortest contiguous piece of s that contains every character of t, counting repeats: if t has two "a"s, the piece needs at least two "a"s.

Return that piece. If no piece qualifies, return the empty string. If several shortest pieces tie, the leftmost one is expected.

Constraints

  • 1 ≤ s.length, t.length ≤ 10⁵
  • s and t have only English letters (upper or lower case)

Examples: pick one to animate

Solutions

TimeO(n + m) SpaceO(1)

Time: Counting t costs O(m). Then right visits each index of s once and left only moves forward, so there are at most 2n steps of O(1) work.

Space: The need table has 128 slots (one per ASCII character), independent of the input length.

Keep need[c] = how many more copies of c the window must collect (it goes negative when the window has spares) and missing = how many wanted letters are still absent. Expand right until missing is 0. Then shrink left as far as the window still covers t, saving the shortest one seen.