Example 1
- Input
- s = "ADOBECODEBANC", t = "ABC"
- Output
- "BANC"
The window "BANC" holds A, B and C, and no shorter window of s holds all three.
Given strings s and t, return the shortest contiguous substring of s that contains every character of t with at least the same multiplicity, or the empty string when no such window exists.
Given strings s and t of lengths m and n, return the shortest contiguous substring of s covering every character of t, including duplicates. Return the empty string when no covering substring exists. Generated test cases guarantee a unique minimum answer.
A substring cannot skip intervening characters. Matching is case-sensitive: A and a are different. With t = "AAB", a window needs two copies of A and one of B; extra letters are allowed. For s = "ADOBECODEBANC" and t = "ABC", ADOBEC qualifies, while DOBE lacks both A and C; the shortest answer is BANC.
m == s.lengthn == t.length1 <= m, n <= 10^5s and t consist of uppercase and lowercase English letters.The window "BANC" holds A, B and C, and no shorter window of s holds all three.
The whole string is the only window and it already qualifies.
The string holds one "a" but two are required, so no window qualifies.
The final three letters contain two uppercase A copies and one C. AC lacks the second required A, so multiplicity matters.
Only uppercase A satisfies the requirement; lowercase a can be discarded.
The whole source lacks D, so a covering window is impossible even though s is longer than t.
Imagine stretching a frame over s until it contains all the letter tokens requested by t. Once sufficient, move its left edge inward to discard irrelevant letters and surplus copies. Removing a letter that leaves too few copies makes the frame insufficient again. In ADOBECODEBANC, ADOBEC first covers ABC; dropping its A forces expansion again. Later, EBANC can discard E to become BANC, but cannot discard B. Counts rather than sets preserve repeated requirements.
Reveal Brute Force: intuition, complexity, and code
t needs; a window is valid exactly when it covers every needed count.For shortest covering windows, pair the sliding window with satisfied-versus-required counters so validity is maintained incrementally instead of rechecked.