Back to DSA

Smallest Window Containing All Characters

hard
Acceptance: 38%
StringsSliding Window

Two strings are given: a text string and a pattern string. Find the shortest contiguous portion of the text that contains every character of the pattern, accounting for multiplicities. If the pattern has a character appearing twice, the window must include at least two occurrences. Return the shortest such window, or an empty string if none exists.

Examples

Example 1:
Input:text = "adobecodebanc", pattern = "abc"
Output:"banc"
Explanation: The window 'banc' starting at index 9 includes 'a', 'b', and 'c', and no shorter window contains all three.
Example 2:
Input:text = "xyz", pattern = "xxyy"
Output:""
Explanation: The pattern requires two x's and two y's, but the text has only one of each.

Hints

00:00
1234567