Given two strings, s
and t
, find the number of distinct subsequences of s
that are equal to t
.
We'll use dynamic programming to solve this problem. Our goal is to build a 2D table to keep track of the number of distinct subsequences. We'll use modulo arithmetic to avoid overflow.
-
Initialization 🌱
- We calculate the lengths of strings
s
andt
and store them asm
andn
, respectively. - If
m
is less thann
, there can be no distinct subsequences, so we return 0.
- We calculate the lengths of strings
-
Dynamic Programming Matrix 📈
- We create a 2D matrix
dp
with dimensionsm x n
to store the intermediate results. - We initialize
dp[0][0]
based on whether the first characters ofs
andt
match.
- We create a 2D matrix
-
Initialize First Column ⬇️
- We iterate over the first column of
dp
(i.e., forj = 0
) and calculate values based on whethers[i]
andt[0]
match:- If they match, we add 1 to the value from the previous row and take the result modulo
1e9 + 7
. - If they don't match, we simply copy the value from the previous row.
- If they match, we add 1 to the value from the previous row and take the result modulo
- We iterate over the first column of
-
Fill the Rest of the Matrix ➡️
- We iterate over the rest of the matrix using nested loops for
i
andj
. - For each cell, we check if
s[i]
andt[j]
match:- If they match, we add the values from the previous row and the diagonal and take the result modulo
1e9 + 7
. - If they don't match, we copy the value from the previous row.
- If they match, we add the values from the previous row and the diagonal and take the result modulo
- We iterate over the rest of the matrix using nested loops for
-
Final Result 🎉
- The final result is stored in
dp[m-1][n-1]
, which represents the number of distinct subsequences.
- The final result is stored in
-
Return Result 🚀
- We return
dp[m-1][n-1]
, which is the answer to the problem.
- We return
The time complexity of this solution is O(m * n), where m
and n
are the lengths of strings s
and t
, respectively.
The space complexity is O(m * n) because we use a 2D matrix of the same dimensions to store intermediate results.