Skip to the solution
HardDSA7 min read

Minimum window substring: how does the sliding window with need/have counters work?

1.0k views

The problem

Question presented to candidate: "In the minimum window substring problem, people keep a 'need' map and a 'have' counter. Explain exactly what each one holds, when each counter changes, and why that makes the window check constant time. Then write the solution in Python."

What a strong answer should cover:

  • need = counts of t; window = counts in the current slice; required = distinct characters of t; have = distinct characters whose window count is at least their need.
  • The window is valid exactly when have == required, so the check is O(1) instead of O(k).
  • have changes only on threshold crossings: +1 when a count reaches its need after adding, -1 when it drops below after removing; spare copies change nothing.
  • The equivalent missing counter over total copies, and the two classic bugs (>= on add, <= on remove).
  • Python specifics: Counter(t) for need and len(need) for required; ch in need before comparing, because characters outside t must not touch have; need.get(c, 0) for the missing-counter variant.

Clarifying questions expected:

  • "Do duplicate characters in t have to be matched with multiplicity?" โ€” this is what makes counts necessary.

Code / implementation expected: Yes โ€” the min-window function in Python, explaining each counter update as it is written.

  • sliding window
  • string
  • Meta

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 ยท 12 sections

Python code

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

PythonTrace every need/have change on ADOBECODEBANC / ABC
Pythonhave vs missing counters, and the two classic off-by-one bugs

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 132 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 do you find the minimum window substring?

Continue