Given a two strings S and T, find count of distinct occurrences of T in S as a subsequence.
Input : S = banana, T = ban Output : 3 T appears in S as below three subsequences. [ban], [ba n], [b an] Input : S = geeksforgeeks, T = ge Output : 6 T appears in S as below three subsequences. [ge], [ ge], [g e], [g e] [g e] and [ g e]
This problem can be recursively defined as below.
// Returns count of subsequences of S that match T // m is length of T and n is length of S subsequenceCount(S, T, n, m) // An empty string is subsequence of all. 1) If length of T is 0, return 1. // Else no string can be a sequence of empty S. 2) Else if S is empty, return 0. 3) Else if last characters of S and T don't match, remove last character of S and recur for remaining return subsequenceCount(S, T, n-1, m) 4) Else (Last characters match), the result is sum of two counts. // Remove last character of S and recur. a) subsequenceCount(S, T, n-1, m) + // Remove last characters of S and T, and recur. b) subsequenceCount(S, T, n-1, m-1)
Since there are overlapping subproblems in above recurrence result, we can apply dynamic programming approach to solve above problem. We create a 2D array mat[m+1][n+1] where m is length of string T and n is length of string S. mat[i][j] denotes the number of distinct subsequence of substring S(1..i) and substring T(1..j) so mat[m][n] contains our solution.
Time Complexity : O(m*n)
Auxiliary Space : O(m*n)
Since mat[i][j] accesses elements of current row and previous row only, we can optimize auxiliary space just by using two rows only reducing space from m*n to 2*n.
This article is contributed by Utkarsh Trivedi. 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.
- Find all distinct subset (or subsequence) sums of an array
- Find all distinct subset (or subsequence) sums of an array | Set-2
- Count Distinct Subsequences
- Count distinct elements in an array
- Count subsequence of length three in a given string
- Count All Palindromic Subsequence in a given String
- Count common subsequence in two strings
- Count all distinct pairs with difference equal to k
- Absolute distinct count in a sorted array
- Count of subsequences having maximum distinct elements
- Maximum length subsequence such that adjacent elements in the subsequence have a common factor
- Printing frequency of each character just after its consecutive occurrences
- Subsequence with maximum odd sum
- Maximum even sum subsequence
- Longest Zig-Zag Subsequence