You are given two strings ‘S’ and ‘T’. Your task is to find the minimum (Contiguous) substring ‘W’ of ‘S’, such that ‘T’ is a subsequence of ‘W’
A subsequence is a sequence that can be derived from another sequence by removing zero or more elements, without changing the order.
A substring is a contiguous part of a string.
For example:For the given string “CodingNinjas”: “Ninja” is a substring while “dinas” is a subsequence.
If there is no such Window in ‘S’ that covers all characters in ‘T’, return an empty string "". If there are multiple such minimum length windows, return the one with the smallest starting index.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows.
The first line of each test case contains the string ‘S’.
The second line of each test case contains the string ‘T’.
Output Format :
For each test case, print the substring of minimum length such that.
Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= S <= 1000
1 <= T <= 100
Time limit: 1 sec
2
rdew
u
abcdebdde
bde
""
bcde
For test case 1 :
Since there is no window in ‘S’ which covers all characters of ‘T’ so therefore we returned an empty string.
For test case 2 :
“bcde” is the substring of minimum length in which we find “bde”. “bdde” is also a substring of minimum length however the index of “bcde” occurs first, therefore we returned bcde
2
hello
eo
goodbye
dy
ello
dby
First, at least try to find a window where the whole string ‘T’ is present. Then try to reduce the size of this window.
We will find the window where we can actually find the whole string ‘T’. Then after that, since we have to return the minimum length window, we will try to shrink this window as much as possible.
The steps are as follows :
^(i) ^(j)
^(i) ^(j)
O( N ^ 2 ), where N is the length of string ‘S’
As we are first moving forward, and then backwards. At ith iteration, in the worst case, we might have to traverse the string till the end. So at each index, if we are traversing the whole string again, complexity will be O(N ^ 2)
We have not used any extra space.