![]() |
VOOZH | about |
Given two strings s1 and s2, count the number of subsequences of string s1 equal to string s2. Return the total count modulo 1e9+7.
Examples:
Input: s1 = "geeksforgeeks", s2 = "gks"
Output: 4
Explanation: 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.
Input: s1 = "problemoftheday", s2 = "geek"
Output: 0
Explanation: No subsequence of string s1 is equal to string s2.
Table of Content
The idea is to recursively process the characters of
s1. For each character, either skip it or include it if it matches the current character ofs2. Count all possible ways that successfully match every character ofs2.
4
Time Complexity: O(2^n)
Auxiliary Space: O(n + m)
The idea is to use Dynamic Programming where
dp[i][j]stores the number of ways to form the firstjcharacters ofs2using the firsticharacters ofs1. For each character ofs1:
- If it matches the current character of
s2, either include it in the subsequence or skip it.- Otherwise, skip the current character of
s1.The final answer is stored in
dp[n][m].
Working of the Approach:
dp where dp[i][j] stores the number of ways to form the first j characters of s2 using the first i characters of s1. dp[i][0] = 1 since an empty string can always be formed. dp[0][j] = 0 for j > 0 since a non-empty string cannot be formed from an empty string. s1. dp[n][m] gives the number of times s2 occurs as a subsequence in s1.4
Time Complexity: O(n * m)
Auxiliary Space: O(n * m)
The idea is to optimize the DP solution by using a single array instead of a 2D table. Here,
dp[j]stores the number of ways to form the firstjcharacters ofs2. For each character ofs1, we traverses2from right to left so that previous states are not overwritten. If the characters match, we either include the current character in the subsequence or skip it. This reduces the space requirement while maintaining the same time complexity.
Working of the Approach:
dp where dp[j] stores the number of ways to form the first j characters of s2. dp[0] = 1 since an empty string can always be formed. s1 one by one. s1, traverse s2 from right to left to avoid overwriting values needed for future computations. dp[j] by adding the ways of forming the previous prefix, i.e., dp[j - 1]. dp[m] gives the number of times s2 occurs as a subsequence in s1.4
Time Complexity: O(n * m)
Auxiliary Space: O(m)