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 holding every kind

Medium · Target 20 minutes · Sliding window· Type asked at

Given a string s, return the length of the shortest substring that contains every distinct character appearing anywhere in s. Return 0 for an empty string.

Examples

InputOutputWhy
s = "aabcbcdbca"4"dbca" holds a, b, c and d.
s = "aaab"2"ab".
s = "zzz"1

Constraints

  • 0 ≤ |s| ≤ 10⁵
  • s is lowercase English letters

Hints

Hint 1

Count the kinds first: that is the target the window must reach.

Hint 2

Once a window covers every kind, so does any window containing it. You want the smallest, so shrink from the left while it still covers.

Hint 3

Record the length inside the shrinking loop, before each removal, not after it.

Where people lose marks

  • Recording the length after the shrinking loop, when the window has just stopped covering.
  • Counting the target kinds from the window instead of from the whole string.
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.