‘ACE’ is a subsequence of ‘ABCDE’ because ‘ACE’ can be formed by deleting ‘B’ and ‘D’ without changing the relative order of characters. ‘ADB’ is not a subsequence of ‘ABCDE’ because we can get ‘ABD’ from ‘ABCDE’ but not ‘ADB’ and in ‘ADB’ relative order of ‘B’ and ‘D’ are different from original strings.
1.Strings ‘STR1’ and ‘STR2’ consists only of English uppercases.
2.Length of string ‘STR2’ will always be greater than or equal to the length of string ‘STR1’.
For example, the given ‘STR1’ is ‘BAE’ and ‘STR2’ is ‘ABADE’.
String ‘STR1’ is a subsequence of string ‘STR2’ because ‘BAE’ can be formed by deleting ‘A’ and ‘D’ from ‘ABADE’ and the relative ordering of the characters of the string ‘ABADE’ persists.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘2*T’ lines represent the ‘T’ test cases.
The first line of each test case contains the string ‘STR1’ on a separate line denoting the subsequence that we need to find in 'STR2' and 'N' is the length of 'STR1'.
The second line of each test case contains the string ‘STR2’ on a separate line denoting the string in which we need to find the subsequence and 'M' is the length of 'STR2'.
For each test case, print a string ‘True’ if ‘STR1’ is a subsequence of ‘STR2’ otherwise print ‘False’.
You are not required to print the output explicitly, it has already been taken care of. Just implement the function.
1 <= T <= 50
1 <= N, M <= 10^4
Where N and M denote the lengths of STR1 and STR2respectively.
Time limit: 1 second
Let’s understand this approach with an example.
Consider ‘STR1’ is ‘BAE’ and ‘STR2’ is ‘ABADE’.
Start with first ‘B’ in ‘STR1’ and find ‘B’ in ‘STR2’ if found then start with ‘A’ and find ‘A’ in ‘STR2’ if ‘A’ exist in ‘STR2’ then check the position of ‘A’ must be after the last find character ‘B’ and repeat the same step for all characters of ‘STR1’.
Basic idea is to use a queue in which we insert all the characters of ‘STR1’ and then check whether the top character is present in ‘STR2’ or not. If the top character of the queue is present then remove it from the queue and check for next the characters that are present in the queue.
Let’s understand this approach with an example.
Consider ‘STR1’ is ‘BAE’ and ‘STR2’ is ‘ABADE’
Iterate ‘STR2’ and check for characters of ‘STR1’ if any point time character of ‘STR1’ and ‘STR2’ are the same then check for the next character of ‘STR1’.
Ninja and Numbers
Longest Palindromic Substring
Next Greater Element II
Cakes
1-3 Palindrome