All problems

Problem 59

Minimum Window Substring

Hard · 30 pts · String, Sliding Window, Hash Table

Problem

You are given two strings S and T. Find the shortest substring of S that contains every character of T, including repeated characters: if T has two A's, the window must contain at least two A's. Upper and lower case letters are different characters. If several shortest windows exist, print the one that starts first; if no window exists, print -1. Use a sliding window with character counts. Extend the right edge until the window covers all of T, then shrink it from the left as much as possible while it still covers T, recording the best window along the way.

Input

Two lines: string S and string T (English letters).

Output

Print the minimum window, or -1.

Constraints

1 <= |S|, |T| <= 100000

Example input

ADOBECODEBANC
ABC

Example output

BANC

Explanation

In "ADOBECODEBANC" with T = "ABC", the window "ADOBEC" contains A, B and C but has length 6. The window "BANC" near the end also contains all three letters and has length 4, which is the shortest possible.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Group Anagrams Count Next: Find All Anagrams in a String