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 email@example.com. 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
- String Range Queries to find the number of subsets equal to a given String
- Queries to find the first non-repeating character in the sub-string of a string
- Queries to find the last non-repeating character in the sub-string of a given string
- Queries to check if string B exists as substring in string A
- Find length of longest subsequence of one string which is substring of another string
- Find number of times a string occurs as a subsequence in given string
- Queries for characters in a repeated string
- Queries to answer the X-th smallest sub-string lexicographically
- Queries for rotation and Kth character of the given string in constant time
- Queries to find the count of vowels in the substrings of the given string
- Count All Palindromic Subsequence in a given String
- Transform a string such that it has abcd..z as a subsequence
- Count subsequence of length three in a given string
Improved By : vt_m