problems / 123

Minimum Window Containing a Multiset

medium sliding-window two-pointers strings 2000 ms · 256 MB

Minimum Window Containing a Multiset

You are given two strings s and t. Find the shortest contiguous substring of s that contains, for every character c, at least as many occurrences of c as t does. In other words, the substring's multiset of characters must be a superset (with multiplicity) of t's multiset of characters.

If several shortest substrings exist, output the one that starts earliest in s. If no substring of s satisfies the requirement, output an empty line instead.

Input

The first line contains the string s (1 ≤ |s| ≤ 10^6). The second line contains the string t (1 ≤ |t| ≤ 10^6).

Both strings consist only of visible printable ASCII characters (character codes 33 through 126 inclusive — letters, digits and punctuation, but no spaces).

Output

Print the shortest substring of s whose character multiset contains t's character multiset, breaking ties by the leftmost starting position. If no such substring exists, print an empty line.

Notes

In the first example, t requires two as and one b, so no valid window can be shorter than |t| = 3. The substring "aab" starting at the second character of s already has exactly two as and one b, achieving that minimum.

Example 1

Input

xaabcabcy
aab

Output

aab

Example 2

Input

abcabc
aaa

Output

Hints · reveal one at a time if you're stuck

Hint 1

This is a sliding-window problem: for each right end, find the smallest valid left end. Since the window only needs to contain enough copies of each character of t, what is the right thing to count?

Hint 2

Keep, for each character, how many more copies the window still needs (it can go negative when the window has surplus), plus one running total of how many required characters are still missing. Move the left end forward only while the window stays valid.

Hint 3

Each time the window becomes valid, shrink it from the left to the tightest valid form, then record it only when it is strictly shorter than the best so far. Strict comparison keeps the leftmost of the shortest windows.

report an issue Prefer your own editor? sooks prep 123 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.