Given a string S and Q queries, each query contains a string T. The task is print “Yes” if T is subsequence of S, else print “No”.
Input : S = "geeksforgeeks" Query 1: "gg" Query 2: "gro" Query 3: "gfg" Query 4: "orf" Output : Yes No Yes No
For each query, using the brute force, start iterating over S looking for the first character of T. As soon as, the first character is found, continue to iterate S now looking for the second character of T and so on (Refer this for details). If manage to find all the character of T, print “Yes”, else “No”. Time complexity is be O(Q*N), N is the length of S.
The efficient approach can be if we know the position of next character of T in S. Then simply skip all the character between current and position of next character and jump to that position. This can be done by making |S| x 26 size matrix and storing the next position of each character from every position of S.
Below is the implementation of above idea :
Yes No Yes No
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Subsequence queries after removing substrings
- Range Queries for Longest Correct Bracket Subsequence
- Find number of times a string occurs as a subsequence in given string
- Find length of longest subsequence of one string which is substring of another string
- Queries for characters in a repeated string
- Queries to answer the X-th smallest sub-string lexicographically
- Count subsequence of length three in a given string
- Count All Palindromic Subsequence in a given String
- Given two strings, find if first string is a subsequence of second
- Transform a string such that it has abcd..z as a subsequence
- Maximum number of removals of given subsequence from a string
- Longest subsequence of the form 0*1*0* in a binary string
- Minimum cost to make a string free of a subsequence
- Maximum length prefix of one string that occurs as subsequence in another
- Find the lexicographically largest palindromic Subsequence of a String
Improved By : vt_m