Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Shortest window containing every letter

Hard · Target 30 minutes · Sliding window · Type asked atMetaGoogle

Given strings s and t, return the length of the shortest contiguous substring of s that contains every character of t, counted with multiplicity (if t has two a's, the substring needs at least two). Return 0 if no such substring exists.

Examples

InputOutputWhy
s = "ADOBECODEBANC", t = "ABC"4"BANC" is the shortest window holding an A, a B and a C.
s = "a", t = "aa"0t needs two a's; s has one.
s = "acbbaca", t = "aba"4"baca": two a's and a b.

Constraints

  • 1 ≤ |s|, |t| ≤ 10⁵
  • Characters are ASCII letters

Hints

Hint 1

Checking every substring is O(n²) windows, each needing a count. A window that already contains t stays valid when it grows; one that does not stays invalid when it shrinks.

Hint 2

So use two pointers. Move the right end until the window contains t. Then move the left end as far as possible while it still does, recording the length, and repeat.

Hint 3

Keep a count of how many of each character the window still needs, and a single number "missing" for the total still needed. A character only reduces "missing" if it was still needed; that keeps every step O(1).

Where people lose marks

  • Comparing whole count tables at every step to test validity. Correct, but it multiplies the running time by the alphabet size; the single "missing" counter avoids it.
  • Decrementing "missing" for every character added, including surplus copies. Only a character that was still needed reduces it.
  • Recording the window length after removing the left character rather than before. The window was valid before the removal.
  • Ignoring multiplicity: treating t as a set of letters makes "aa" look satisfied by a single a.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.