strings
sliding-window
hashmap
Given strings s and t, return the shortest contiguous substring of s that contains every character from t with at least the same multiplicity. If no such substring exists, return the empty string. If several windows have the same minimum length, returning any one of them is acceptable — the supplied tests use unique answers.
Input / output
- Input:
s: string,t: string - Output: the minimum covering substring, or
""if impossible
Examples
s = "ADOBECODEBANC",t = "ABC"returns"BANC".s = "a",t = "a"returns"a".s = "a",t = "aa"returns""becausesdoes not contain twoacharacters.
Constraints
1 <= t.length <= s.length <= 10^5for the canonical problemsandtmay contain uppercase letters, lowercase letters, and digits
Target complexity
- Aim for
O(|s| + |t|)time andO(|alphabet|)extra space.
Hints
- Count how many of each character
tneeds before you scans. - Expand a right pointer until the window is valid, then shrink the left pointer as far as possible while keeping it valid.
Follow-up
How would you adapt the technique if the requirement were "cover all characters from t in order" instead of with arbitrary order?
Examples
Example 1
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Example 2
Input: s = "a", t = "a"
Output: "a"
Example 3
Input: s = "a", t = "aa"
Output: ""
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.