You are given two strings S and X containing random characters. Your task is to find the smallest substring in S which contains all the characters present in X.
Example:
Let S = “abdd” and X = “bd”.
The windows in S which contain all the characters in X are: 'abdd', 'abd', 'bdd', 'bd'.
Out of these, the smallest substring in S which contains all the characters present in X is 'bd'.
All the other substring have a length larger than 'bd'.
The very first line of input contains an integer T denoting the number of test cases.
The first line of every test case contains the string S.
The second line of every test case contains the string X.
Output format:
For each test case, print the smallest window in S which contains all the characters present in X, in a separate line.
Note:
There is always a valid window in S which contains all the characters of X.
You do not need to print anything, it has already been taken care of. Just implement the given function.
Note:
In case of multiple answers, print only the substring that occurs first.
For example: for the string S = 'cbbbc' and X = 'bc', there are 2 possible answers i.e. 'cb' and 'bc', your code should print 'cb'.
1 <= T <= 10
1 <= |S|, |X| <= 10^5
Here, |S| denotes the length of string S and |X| denotes the length of string X.
Time Limit: 1 sec
2
cn
c
kmmdnj
mj
c
mdnj
For the first test case when S = 'cn' and X = 'c'.
The substrings in S which contain all the characters present in X are: 'cn' and 'n'. Out of these, the smallest substring is 'c'.
For the second test case when S = 'kmmdnj' and X = 'mj'.
The substrings in S which contain all the characters present in X are: 'kmmdnj', 'mmdnj', 'mdnj'. Out of these, the smallest substring is 'mdnj'.
3
ilovecodingninjas
oiln
aabaac
aba
AbbaBxA
BA
lovecodin
aab
BxA
A simple and intuitive approach could be to generate all the possible substrings of string S and choose the smallest substring which contains all the characters present in X.
A simple and intuitive approach could be to generate all the possible substrings of string S and choose the smallest substring which contains all the characters present in X.
This can be done by the following approach:
O((|S| ^ 2) * |X|) per test case.
Note: Here, |S| denotes the length of string S, and |X| denotes the length of string X.
In the worst case, we are generating all the possible substrings of string S. Each substring is compared with the string X to check whether it is valid or not; this requires O(|X|) operations, assuming that accessing the hashtable requires constant time operation.
O(1) per test case.
In the worst case, extra space is required by the hash tables. In the worst case, the size of the hashtable would be equal to 26 (Number of English alphabets); hence, the space complexity remains constant.