Maintained by Vikas Dulgunde, software engineer
You are given a source string `s` and a target string `t`. A valid window is any contiguous slice of `s` that holds at least as many of each character as `t` requires. If `t` has two copies of a character, the window must contain at least two of that character as well.
Among all valid windows, you want the one with the fewest characters. The window only needs to cover `t`; it may contain extra characters that `t` never asks for, and those extras do not disqualify it.
Return the actual substring, not its length or its bounds. When `s` cannot cover everything `t` needs, return the empty string. The guarantee in interviews is usually that the answer is unique, but the shortest-window rule already decides ties by length.
The target is a single linear pass: the work should scale with `|s| + |t|`, not with the number of possible windows.
Reading left to right, the first window that covers A, B, and C runs from the first A to the C, but it is long. The window "BANC" near the end also covers all three and is shorter, so it wins.
The leading extra A is not needed, so the optimal window drops it and lands on the trailing "ABC", which covers one A, one B, and one C with nothing to spare.
The target wants two copies of 'a' but `s` only offers one, so no window can ever cover `t` and the answer is the empty string.
Visible test cases
Counts, not just presence, drive this problem. Build a frequency table of what `t` needs so you can tell when a window has enough of every character, duplicates included.
Grow a window by moving its right edge forward and adding each new character. Once the window covers all of `t`, stop growing and instead try to shrink it from the left while it still stays valid.
Track how many distinct required characters are currently satisfied rather than rescanning the whole table each step. A character becomes satisfied the moment its in-window count reaches its required count, and unsatisfied the moment a shrink drops it below.
Try every start and end position, and for each candidate substring check whether it covers all the character counts that `t` demands.
Keep one window that expands on the right and contracts on the left. Track how many required characters are fully satisfied so you know in constant time whether the window currently covers `t`.