iq.lab
Python starts when a code cell comes near or you run one
hardSliding windowHash maps and sets target 40 min

Smallest window that covers a set of letters

You get two strings, text and letters. A substring of text (a block of consecutive characters) covers letters if it holds every character of letters at least as many times as letters does. To cover "AAB", a substring needs two A's and one B, and it may hold other characters too.

Return the shortest substring of text that covers letters. If several shortest ones exist, return the one that starts first. If none exists, return the empty string "".

Example 1
Inputtext = "AXBYCAB", letters = "ABC"Output"CAB"

"AXBYC" covers A, B and C, but the shorter "CAB" at the end covers them too. Three letters need at least three characters, so nothing is shorter.

Example 2
Inputtext = "BAAXB", letters = "AAB"Output"BAA"

Repeats count: the window needs two A's. "BAA" has them, and so does "AAXB", which is longer.

Example 3
Inputtext = "A", letters = "AA"Output""

The text has only one A, so nothing covers two.

Constraints
  • 1 ≤ len(text) ≤ 105

  • 1 ≤ len(letters) ≤ 105

  • Both strings hold upper and lower case English letters. Case matters: "a" does not cover "A".

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.