Ctrl K

Shortest Covering Window

Hard
You get two strings, text and letters. Find the shortest contiguous piece of text that contains every character of letters, counting repeats: if a letter appears twice in letters, the piece must contain it at least twice as well. Uppercase and lowercase letters are different characters. Return that piece. If several shortest pieces qualify, return the one that starts furthest to the left. If no piece qualifies, return the empty string. Try to solve it in O(len(text) + len(letters)).
Example 1
text='xmaybxazmy', letters='mzy' → 'zmy'

The piece "zmy" (positions 7–9) contains m, z and y, and no shorter piece does.

Example 2
text='bob', letters='Bo' → ''

Case matters: there is no capital B in the text, so the answer is the empty string.

Example 3
text='kaakak', letters='kka' → 'kak'

We need two k's and one a. Among pieces of length 3 only "kak" works: "kaa", "aak" and "aka" each have a single k.

Constraints
  • 1 ≤ len(text), len(letters) ≤ 10⁵
  • text and letters consist of uppercase and lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWord Blocks in Any Order HardLongest Clean Stretch HardEven Stretches Without Jumps HardWindows Covering a Letter Set: Large Input HardA Letter Reaches k Repeats: Large Input Hard
loading Python…
Input
text='xmaybxazmy', letters='mzy'
Expected
'zmy'

Run checks the first 3 tests in your browser. Submit checks all 83 tests on the server, hidden ones included.