hardSliding WindowAmazonMetaMicrosoft
Minimum Keyring Window
A set of required keys and a long chain of pouches. Find the shortest contiguous stretch of pouches whose multiset of keys covers everything you need.
Given strings `s` and `t`, return the smallest substring of `s` whose character counts cover every character of `t`. Return empty if none.
Choose approach
A
0D
1O
2B
3E
4C
5O
6D
7E
8B
9A
10N
11C
12Mapneed
A→1
B→1
C→1
1/28
Narrationstep 1 of 28
Need "ABC" → 3 distinct letters. Grow hi until all required counts are met, then shrink from lo for minimality.
Variables
required=3
formed=0
lo=0
How to think about it
- Required = number of distinct chars in t.
- Grow hi; whenever have[c] hits need[c] exactly, increment `formed`.
- When formed == required, try to shrink from lo for a smaller valid window.
- Record (lo, len) whenever the window beats the best; return the best substring at the end.
Edge cases to catch in interview
- t longer than s or empty → empty answer.
- Multiple characters repeated in t — need count matters, not just presence.
- Answer unique even on ties (first smallest).
Examples
Example 1
"BANC"{"s":"ADOBECODEBANC","t":"ABC","values":["A","D","O","B","E","C","O","D","E","B","A","N","C"]}
Example 2
"a"{"s":"a","t":"a","values":["a"]}
Example 3
""{"s":"a","t":"aa","values":["a"]}
Not enough a's.
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed