Skip to the solution
HardDSA7 min read

How do you find the minimum window substring?

932 views

The problem

Question presented to candidate: "Given two strings s and t, return the smallest substring of s that contains every character of t, including duplicates. If there is none, return an empty string. For s = 'ADOBECODEBANC' and t = 'ABC' the answer is 'BANC'. Please solve it in Python in linear time."

What a strong answer should cover:

  • Brute force over all substrings is at least O(nยฒ); the expected answer is a variable-size sliding window: expand right until valid, shrink left while valid, O(|s| + |t|).
  • Frequency maps for t (need) and the window, because duplicates in t matter.
  • An O(1) validity check with need/have counters: have changes only when a count crosses its threshold.
  • Recording the answer inside the shrink loop, the leftmost-on-ties rule, and the no-window case.
  • Python specifics: collections.Counter(t) builds the need map in one line and returns 0 for missing keys; float("inf") as the 'no window yet' length; slice once at the end.

Clarifying questions expected:

  • "Do duplicate characters in t have to appear that many times?"
  • "What do I return if no window exists, or if t is empty?"

Code / implementation expected: Yes โ€” a min_window(s, t) function in Python with expand/shrink and need/have counters.

  • strings
  • sliding-window

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMinimum window substring on eight inputs
PythonBrute force vs sliding window: same answers, far fewer steps

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 133 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

How does the Floyd-Warshall algorithm work?

Continue