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 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.
- Number of subsequences of the form a^i b^j c^k
- Minimum number of swaps required to sort an array
- Count All Palindromic Subsequence in a given String
- Print all longest common sub-sequences in lexicographical order
- Number of permutation with K inversions
- Count all increasing subsequences
- Longest repeating and non-overlapping substring
- Find minimum sum such that one of every three consecutive elements is taken
- Count Distinct Subsequences
- Count digit groupings of a number with given constraints
- Find number of times a string occurs as a subsequence in given string
- Longest Common Increasing Subsequence (LCS + LIS)
- Wildcard Pattern Matching
- Find if a string is interleaved of two other strings | DP-33
- Longest Common Subsequence | DP-4
Improved By : vt_m