CodeArchon

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
0
D
1
O
2
B
3
E
4
C
5
O
6
D
7
E
8
B
9
A
10
N
11
C
12
Mapneed
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.

1def minimum_keyring_window(s: str, t: str) -> str:
2 if not s or not t:
3 return ""
4 need: dict[str, int] = {}
5 for c in t:
6 need[c] = need.get(c, 0) + 1
7 required = len(need)
8 formed = 0
9 have: dict[str, int] = {}
10 lo = best_lo = 0
11 best_len = float("inf")
12 for hi, c in enumerate(s):
13 have[c] = have.get(c, 0) + 1
14 if c in need and have[c] == need[c]:
15 formed += 1
16 while formed == required:
17 if hi - lo + 1 < best_len:
18 best_len, best_lo = hi - lo + 1, lo
19 d = s[lo]
20 have[d] -= 1
21 if d in need and have[d] < need[d]:
22 formed -= 1
23 lo += 1
24 return "" if best_len == float("inf") else s[best_lo:best_lo + best_len]
Variables
required=3
formed=0
lo=0

How to think about it

  1. Required = number of distinct chars in t.
  2. Grow hi; whenever have[c] hits need[c] exactly, increment `formed`.
  3. When formed == required, try to shrink from lo for a smaller valid window.
  4. 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