30(May) String Subsequence
30. String Subsequence
The problem can be found at the following link: Question Link
Problem Description
Given two strings, s1 and s2, count the number of subsequences of string s1 equal to string s2. Return the total count modulo (10^9 + 7).
Example 1:
Input:
s1 = "geeksforgeeks"
s2 = "gks"Output:
4Explanation: We can pick characters from s1 as a subsequence from indices {0,3,4}, {0,3,12}, {0,11,12} and {8,11,12}. So total 4 subsequences of s1 that are equal to s2.
My Approach
Initialization:
Create a memoization table
memoof size(n+1) x (m+1)initialized to -1, wherenis the length ofs1andmis the length ofs2.Define the modulo value
modas (10^9 + 7).
Dynamic Programming Function:
Use a recursive function
dp(i, j)to calculate the number of ways to match the firsticharacters ofs1with the firstjcharacters ofs2.Base cases:
If
j == 0, return 1 since an emptys2can be matched in one way.If
i == 0, return 0 since a non-emptys2cannot be matched with an emptys1.
Recursive cases:
If
s1[i-1] == s2[j-1], updatememo[i][j]with the sum ofdp(i-1, j-1)anddp(i-1, j)modulomod.Otherwise, set
memo[i][j]todp(i-1, j)modulomod.
Return:
Return
dp(n, m)wherenis the length ofs1andmis the length ofs2.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n * m), where
nandmare the lengths of the stringss1ands2respectively. This is due to the nested loops iterating over the lengths of the strings.Expected Auxiliary Space Complexity: O(n * m), due to the memoization table storing results for each subproblem of sizes up to
nandm.
Code
C++
Java
Python
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated