Given two strings A and B, the problem is to find if string B will be a subsequence of of string A if we remove the substring [A[i]..A[j]] from string A. Assume that there are Q queries giving the indices i and j and each query is independent of the other.
Input : A = abcabcxy, B = acy Q = 2 i = 2, j = 5 i = 3, j = 6 Output : Yes No Explanation : In the first query we remove A..A, getting acxy and acy is its subsequence. In the second query we remove A..A, getting abxy but acy is not its subsequence.
A brute force approach is, for each query remove the required substring from A and check if B is a subsequence of A, but is inefficient because we have to modify the string A for each query and also check if string B is its subsequence.
A more efficient approach is to do preprocessing on the strings as we have to encounter multiple queries. We can store the number of characters of string B that matches till each index of string A in both the forward and backward directions, in two separate arrays. Finally we can say the answer is Yes, if the following equation holds, otherwise No:
forward[i-1] + backward[j+1] >= length(B).
This works because we are removing A[i]..A[j] from A and want to know the sum of number of characters of B that match in A
from A..A[i-1] and A[j+1]..A[len], which is a subsequence if this sum is atleast the length of string B.
Following is the implementation of the above approach:
The time complexity of the above approach is O(n + q), where q is the number of queries and n is the length of string A.
- Queries for frequencies of characters in substrings
- Queries on subsequence of string
- Range Queries for Longest Correct Bracket Subsequence
- Array range queries over range queries
- Removing punctuations from a given string
- Removing elements between the two zeros
- Number of substrings of a string
- Replace two substrings (of a string) with each other
- Number of substrings divisible by 8 but not by 3
- Find substrings that contain all vowels
- Count substrings with same first and last characters
- Removing spaces from a string using Stringstream
- Number of substrings with count of each character as k
- Number of substrings of one string present in other
- Count Substrings with equal number of 0s, 1s and 2s
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.