Given two strings s and t, return the number of distinct subsequences of s that equal t.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde" while "aec" is not.
The task is to count how many different ways we can form t from s by deleting some (or no) characters from s. Return the result modulo 109+7.
Input: s = "axbxax", t = "axa"
Output: 2
Explanation: In the string "axbxax", there are two distinct subsequences "axa":
(a)(x)bx(a)x
(a)xb(x)(a)x
Input: s = "babgbag", t = "bag"
Output: 5
Explanation: In the string "babgbag", there are five distinct subsequences "bag":
(ba)(b)(ga)(g)
(ba)(bg)(ag)
(bab)(ga)(g)
(bab)(g)(ag)
(babg)(a)(g)
Input: s = "abcde", t = "ace"
We have to find distinct subsequences of 's' in 't'. As there is no uniformity in data, there is no other way to find out than to try out all possible ways. To do so we will need to use recursion.
(Case 1)When the characters match: If(s[i] == t[j]), let’s understand it with the following example:
s[i] == t[j], now as the characters at i and j match, we would want to check the possibility of the remaining characters of str2 in str1 therefore we reduce the length of both the strings by 1 and call the function recursively.
Now, if we only make the above single recursive call, we are rejecting the opportunities to find more than one subsequences because it can happen that the jth character may match with more characters in s[0…i-1], for example where there are more occurrences of ‘g’ in str1 from which also an answer needs to be explored.
To explore all such possibilities, we make another recursive call in which we reduce the length of the s string by 1 but keep the t string the same, i.e we call f(i-1,j).
(Case 2) When the characters don’t match: If(s[i] != t[j]), it means that we don’t have any other choice than to try the next character of s and match it with the current character t.
This can be summarized as :
/*It is pseudocode and it is not related
to any specific programming language */
f(i, j){
if(s[i] == t[j]){
return f(i-1, j-1) + f(i-1, j)
}
else
return f(i-1, j)
}
#include <bits/stdc++.h>
using namespace std;
class Solution{
private:
const int prime = 1e9 + 7;
int countUtil(string s1, string s2, int ind1, int ind2) {
/* If s2 has been completely matched,
return 1 (found a valid subsequence)*/
if (ind2 < 0)
return 1;
/* If s1 has been completely traversed
but s2 hasn't, return 0*/
if (ind1 < 0)
return 0;
int result = 0;
/* If the characters match, consider two options:
either leave one character in s1 and s2 or leave
one character in s1 and continue matching s2*/
if (s1[ind1] == s2[ind2]) {
int leaveOne = countUtil(s1, s2, ind1 - 1, ind2 - 1);
int stay = countUtil(s1, s2, ind1 - 1, ind2);
result = (leaveOne + stay) % prime;
} else {
/* If characters don't match, just leave
one character in s1 and continue matching s2*/
result = countUtil(s1, s2, ind1 - 1, ind2);
}
// Return the result
return result;
}
public:
/* Function to count the number of
distinct subsequences of s in t*/
int distinctSubsequences(string s, string t){
int lt = s.size();
int ls = t.size();
return countUtil(s, t, lt - 1, ls - 1);
}
};
int main() {
string s1 = "babgbag";
string s2 = "bag";
//Create an instace of Solution class
Solution sol;
// Print the result
cout << "The Count of Distinct Subsequences is " << sol.distinctSubsequences(s1, s2);
return 0;
}
import java.util.*;
class Solution {
private static final int prime = (int)(1e9 + 7);
/* Function to count the number of
distinct subsequences of s2 in s1*/
private int countUtil(String s1, String s2, int ind1, int ind2) {
/* If s2 has been completely matched,
return 1 (found a valid subsequence)*/
if (ind2 < 0)
return 1;
/* If s1 has been completely traversed
but s2 hasn't, return 0*/
if (ind1 < 0)
return 0;
int result = 0;
/* If the characters match, consider two options:
either leave one character in s1 and s2 or leave
one character in s1 and continue matching s2*/
if (s1.charAt(ind1) == s2.charAt(ind2)) {
int leaveOne = countUtil(s1, s2, ind1 - 1, ind2 - 1);
int stay = countUtil(s1, s2, ind1 - 1, ind2);
result = (leaveOne + stay) % prime;
} else {
/* If characters don't match, just leave
one character in s1 and continue matching s2*/
result = countUtil(s1, s2, ind1 - 1, ind2);
}
// Return the result
return result;
}
/* Function to count the number of
distinct subsequences of s in t*/
public int distinctSubsequences(String s, String t) {
int lt = s.length();
int ls = t.length();
return countUtil(s, t, lt - 1, ls - 1);
}
public static void main(String[] args) {
String s1 = "babgbag";
String s2 = "bag";
//Create an instace of Solution class
Solution sol = new Solution();
// Print the result
System.out.println("The Count of Distinct Subsequences is " + sol.distinctSubsequences(s1, s2));
}
}
class Solution:
prime = 10**9 + 7
""" Function to count the number of
distinct subsequences of s2 in s1"""
def countUtil(self, s1, s2, ind1, ind2):
""" If s2 has been completely matched,
return 1 (found a valid subsequence)"""
if ind2 < 0:
return 1
""" If the result for this state has
already been calculated, return it"""
if ind1 < 0:
return 0
result = 0
""" If the characters match, consider two options:
either leave one character in s1 and s2 or leave
one character in s1 and continue matching s2"""
if s1[ind1] == s2[ind2]:
leaveOne = self.countUtil(s1, s2, ind1 - 1, ind2 - 1)
stay = self.countUtil(s1, s2, ind1 - 1, ind2)
result = (leaveOne + stay) % self.prime
else:
""" If characters don't match, just leave
one character in s1 and continue matching s2"""
result = self.countUtil(s1, s2, ind1 - 1, ind2)
# Return the result
return result
""" Function to count the number of
distinct subsequences of s in t"""
def distinctSubsequences(self, s, t):
lt = len(s)
ls = len(t)
return self.countUtil(s, t, lt - 1, ls - 1)
s1 = "babgbag"
s2 = "bag"
#Create an instace of Solution class
sol = Solution()
# Print the result
print(f"The Count of Distinct Subsequences is {sol.distinctSubsequences(s1, s2)}")
class Solution {
constructor() {
this.prime = 1000000007;
}
/* Function to count the number of
distinct subsequences of s2 in s1*/
countUtil(s1, s2, ind1, ind2) {
/* If s2 has been completely matched,
return 1 (found a valid subsequence)*/
if (ind2 < 0) return 1;
/* If s1 has been completely traversed
but s2 hasn't, return 0*/
if (ind1 < 0) return 0;
let result = 0;
/* If the characters match, consider two options:
either leave one character in s1 and s2 or leave
one character in s1 and continue matching s2*/
if (s1[ind1] === s2[ind2]) {
let leaveOne = this.countUtil(s1, s2, ind1 - 1, ind2 - 1);
let stay = this.countUtil(s1, s2, ind1 - 1, ind2);
result = (leaveOne + stay) % this.prime;
} else {
/* If characters don't match, just leave
one character in s1 and continue matching s2*/
result = this.countUtil(s1, s2, ind1 - 1, ind2);
}
// Return the result
return result;
}
/* Function to count the number of
distinct subsequences of s in t*/
distinctSubsequences(s, t) {
let lt = s.length;
let ls = t.length;
return this.countUtil(s, t, lt - 1, ls - 1);
}
}
let s1 = "babgbag";
let s2 = "bag";
//Create an instace of Solution class
let sol = new Solution();
// Print the result
console.log("The Count of Distinct Subsequences is " + sol.distinctSubsequences(s1, s2));
If we draw the recursion tree, we will see that there are overlapping subproblems. Hence the DP approaches can be applied to the recursive solution.
The dp array shows the calculations of the subproblems, initialize it with -1 to show that no subproblem is solved yet.
#include <bits/stdc++.h>
using namespace std;
class Solution{
private:
const int prime = 1e9 + 7;
int countUtil(string s1, string s2, int ind1, int ind2, vector<vector<int>>& dp) {
/* If s2 has been completely matched,
return 1 (found a valid subsequence)*/
if (ind2 < 0)
return 1;
/* If s1 has been completely traversed
but s2 hasn't, return 0*/
if (ind1 < 0)
return 0;
/* If the result for this state has
already been calculated, return it*/
if (dp[ind1][ind2] != -1)
return dp[ind1][ind2];
int result = 0;
/* If the characters match, consider two options:
either leave one character in s1 and s2 or leave
one character in s1 and continue matching s2*/
if (s1[ind1] == s2[ind2]) {
int leaveOne = countUtil(s1, s2, ind1 - 1, ind2 - 1, dp);
int stay = countUtil(s1, s2, ind1 - 1, ind2, dp);
result = (leaveOne + stay) % prime;
} else {
/* If characters don't match, just leave
one character in s1 and continue matching s2*/
result = countUtil(s1, s2, ind1 - 1, ind2, dp);
}
// Store the result and return it
dp[ind1][ind2] = result;
return result;
}
public:
/* Function to count the number of
distinct subsequences of s in t*/
int distinctSubsequences(string s, string t){
int lt = s.size();
int ls = t.size();
vector<vector<int>> dp(lt, vector<int>(ls, -1));
return countUtil(s, t, lt - 1, ls - 1, dp);
}
};
int main() {
string s1 = "babgbag";
string s2 = "bag";
//Create an instace of Solution class
Solution sol;
// Print the result
cout << "The Count of Distinct Subsequences is " << sol.distinctSubsequences(s1, s2);
return 0;
}
import java.util.*;
class Solution {
private static final int prime = (int)(1e9 + 7);
/* Function to count the number of
distinct subsequences of s2 in s1*/
private int countUtil(String s1, String s2, int ind1, int ind2, int[][] dp) {
/* If s2 has been completely matched,
return 1 (found a valid subsequence)*/
if (ind2 < 0)
return 1;
/* If s1 has been completely traversed
but s2 hasn't, return 0*/
if (ind1 < 0)
return 0;
/* If the result for this state has
already been calculated, return it*/
if (dp[ind1][ind2] != -1)
return dp[ind1][ind2];
int result = 0;
/* If the characters match, consider two options:
either leave one character in s1 and s2 or leave
one character in s1 and continue matching s2*/
if (s1.charAt(ind1) == s2.charAt(ind2)) {
int leaveOne = countUtil(s1, s2, ind1 - 1, ind2 - 1, dp);
int stay = countUtil(s1, s2, ind1 - 1, ind2, dp);
result = (leaveOne + stay) % prime;
} else {
/* If characters don't match, just leave
one character in s1 and continue matching s2*/
result = countUtil(s1, s2, ind1 - 1, ind2, dp);
}
// Store the result and return it
dp[ind1][ind2] = result;
return result;
}
/* Function to count the number of
distinct subsequences of s in t*/
public int distinctSubsequences(String s, String t) {
int lt = s.length();
int ls = t.length();
int[][] dp = new int[lt][ls];
for (int[] row : dp) {
Arrays.fill(row, -1);
}
return countUtil(s, t, lt - 1, ls - 1, dp);
}
public static void main(String[] args) {
String s1 = "babgbag";
String s2 = "bag";
//Create an instace of Solution class
Solution sol = new Solution();
// Print the result
System.out.println("The Count of Distinct Subsequences is " + sol.distinctSubsequences(s1, s2));
}
}
class Solution:
prime = 10**9 + 7
""" Function to count the number of
distinct subsequences of s2 in s1"""
def countUtil(self, s1, s2, ind1, ind2, dp):
""" If s2 has been completely matched,
return 1 (found a valid subsequence)"""
if ind2 < 0:
return 1
""" If the result for this state has
already been calculated, return it"""
if ind1 < 0:
return 0
""" If the result for this state has
already been calculated, return it"""
if dp[ind1][ind2] != -1:
return dp[ind1][ind2]
result = 0
""" If the characters match, consider two options:
either leave one character in s1 and s2 or leave
one character in s1 and continue matching s2"""
if s1[ind1] == s2[ind2]:
leaveOne = self.countUtil(s1, s2, ind1 - 1, ind2 - 1, dp)
stay = self.countUtil(s1, s2, ind1 - 1, ind2, dp)
result = (leaveOne + stay) % self.prime
else:
""" If characters don't match, just leave
one character in s1 and continue matching s2"""
result = self.countUtil(s1, s2, ind1 - 1, ind2, dp)
# Store the result and return it
dp[ind1][ind2] = result
return result
""" Function to count the number of
distinct subsequences of s in t"""
def distinctSubsequences(self, s, t):
lt = len(s)
ls = len(t)
dp = [[-1] * ls for _ in range(lt)]
return self.countUtil(s, t, lt - 1, ls - 1, dp)
s1 = "babgbag"
s2 = "bag"
#Create an instace of Solution class
sol = Solution()
# Print the result
print(f"The Count of Distinct Subsequences is {sol.distinctSubsequences(s1, s2)}")
class Solution {
constructor() {
this.prime = 1000000007;
}
/* Function to count the number of
distinct subsequences of s2 in s1*/
countUtil(s1, s2, ind1, ind2, dp) {
/* If s2 has been completely matched,
return 1 (found a valid subsequence)*/
if (ind2 < 0) return 1;
/* If s1 has been completely traversed
but s2 hasn't, return 0*/
if (ind1 < 0) return 0;
/* If the result for this state has
already been calculated, return it*/
if (dp[ind1][ind2] !== -1) return dp[ind1][ind2];
let result = 0;
/* If the characters match, consider two options:
either leave one character in s1 and s2 or leave
one character in s1 and continue matching s2*/
if (s1[ind1] === s2[ind2]) {
let leaveOne = this.countUtil(s1, s2, ind1 - 1, ind2 - 1, dp);
let stay = this.countUtil(s1, s2, ind1 - 1, ind2, dp);
result = (leaveOne + stay) % this.prime;
} else {
/* If characters don't match, just leave
one character in s1 and continue matching s2*/
result = this.countUtil(s1, s2, ind1 - 1, ind2, dp);
}
// Store the result and return it
dp[ind1][ind2] = result;
return result;
}
/* Function to count the number of
distinct subsequences of s in t*/
distinctSubsequences(s, t) {
let lt = s.length;
let ls = t.length;
let dp = Array.from({ length: lt }, () => Array(ls).fill(-1));
return this.countUtil(s, t, lt - 1, ls - 1, dp);
}
}
let s1 = "babgbag";
let s2 = "bag";
//Create an instace of Solution class
let sol = new Solution();
// Print the result
console.log("The Count of Distinct Subsequences is " + sol.distinctSubsequences(s1, s2));
In order to convert a recursive code to tabulation code, we try to convert the recursive code to tabulation and here are the steps:
Therefore, we set the base condition (keep in mind 1-based indexing), we set the first column’s value as 1 and the first row as 1.
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
const int prime = 1e9 + 7;
/* Function to count the number of
distinct subsequences of s2 in s1*/
int distinctSubsequences(string s, string t){
int n = s.size();
int m = t.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
/* Initialize the first row: empty string s2
can be matched with any non-empty s1 in one way*/
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
/* Initialize the first column:
s1 can't match any non-empty s2*/
for (int i = 1; i <= m; i++) {
dp[0][i] = 0;
}
// Fill in the DP array
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s[i - 1] == t[j - 1]) {
/* If the characters match, consider two options:
either leave one character in s and t or leave
one character in s and continue matching t*/
dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % prime;
} else {
/* If the characters don't match, we can
only leave the current character in s*/
dp[i][j] = dp[i - 1][j];
}
}
}
/* The value at dp[n][m] contains
the count of distinct subsequences*/
return dp[n][m];
}
};
int main() {
string s1 = "babgbag";
string s2 = "bag";
//Create an instace of Solution class
Solution sol;
// Print the result
cout << "The Count of Distinct Subsequences is " << sol.distinctSubsequences(s1, s2);
return 0;
}
import java.util.*;
class Solution {
private static final int prime = (int)(1e9 + 7);
/* Function to count the number of
distinct subsequences of s in t*/
public int distinctSubsequences(String s, String t) {
int n = s.length();
int m = t.length();
int[][] dp = new int[n + 1][m + 1];
/* Initialize the first row: empty string t can
be matched with any non-empty s in one way*/
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
/* Initialize the first column:
s can't match any non-empty t*/
for (int i = 1; i <= m; i++) {
dp[0][i] = 0;
}
// Fill in the DP array
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
/* If the characters match, consider two options:
either leave one character in s and t or leave
one character in s and continue matching t*/
dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % prime;
} else {
/* If the characters don't match, we can
only leave the current character in s*/
dp[i][j] = dp[i - 1][j];
}
}
}
/* The value at dp[n][m] contains
the count of distinct subsequences*/
return dp[n][m];
}
public static void main(String[] args) {
String s1 = "babgbag";
String s2 = "bag";
//Create an instace of Solution class
Solution sol = new Solution();
// Print the result
System.out.println("The Count of Distinct Subsequences is " + sol.distinctSubsequences(s1, s2));
}
}
class Solution:
prime = 10**9 + 7
""" Function to count the number of
distinct subsequences of s in t"""
def distinctSubsequences(self, s, t):
n = len(s)
m = len(t)
dp = [[0] * (m + 1) for _ in range(n + 1)]
""" Initialize the first row: empty string t can
be matched with any non-empty s in one way"""
for i in range(n + 1):
dp[i][0] = 1
""" Initialize the first column:
s can't match any non-empty t"""
for i in range(1, m + 1):
dp[0][i] = 0
# Fill in the DP array
for i in range(1, n + 1):
for j in range(1, m + 1):
if s[i - 1] == t[j - 1]:
"""If the characters match, consider two options:
either leave one character in s and t or leave
one character in s and continue matching t"""
dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % self.prime
else:
""" If the characters don't match, we can
only leave the current character in s"""
dp[i][j] = dp[i - 1][j]
""" The value at dp[n][m] contains
the count of distinct subsequences"""
return dp[n][m]
s1 = "babgbag"
s2 = "bag"
#Create an instace of Solution class
sol = Solution()
# Print the result
print(f"The Count of Distinct Subsequences is {sol.distinctSubsequences(s1, s2)}")
class Solution {
constructor() {
this.prime = 1000000007;
}
/* Function to count the number of
distinct subsequences of s in t*/
distinctSubsequences(s, t) {
let n = s.length;
let m = t.length;
let dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill(0));
/* Initialize the first row: empty string t can
be matched with any non-empty s in one way*/
for (let i = 0; i <= n; i++) {
dp[i][0] = 1;
}
/* Initialize the first column:
s can't match any non-empty t*/
for (let i = 1; i <= m; i++) {
dp[0][i] = 0;
}
// Fill in the DP array
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
if (s[i - 1] === t[j - 1]) {
/* If the characters match, consider two options:
either leave one character in s and t or leave
one character in s and continue matching t*/
dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % this.prime;
} else {
/* If the characters don't match, we can
only leave the current character in s*/
dp[i][j] = dp[i - 1][j];
}
}
}
/* The value at dp[n][m] contains
the count of distinct subsequences*/
return dp[n][m];
}
}
let s1 = "babgbag";
let s2 = "bag";
//Create an instace of Solution class
let sol = new Solution();
// Print the result
console.log("The Count of Distinct Subsequences is " + sol.distinctSubsequences(s1, s2));
If we observe the relation obtained in the tabulation approach, dp[i][j] = dp[i-1][j-1] + dp[i-1][j] or dp[i][j] = dp[i-1][j]. We see that to calculate a value of a cell of the dp array, we need only the previous row values (say prev). So, we don’t need to store an entire array. Hence we can space optimize it. We will be space-optimizing this solution using only one row.
If we see the values required, dp[i-1][j-1] and dp[i-1][j], we can say that if we are at a column j, we will only require the values shown in the grey box from the previous row and other values will be from the cur row itself. So we do not need to store an entire array for it.
If we need only two values from the prev row, there is no need to store an entire row. We can work a bit smarter.
We can use the cur row itself to store the required value in the following way:
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
const int prime = 1e9 + 7;
/* Function to count the number of
distinct subsequences of s2 in s1*/
int distinctSubsequences(string s, string t){
int n = s.size();
int m = t.size();
/* Declare an array to store the count of
distinct subsequences for each character in t*/
vector<int> prev(m + 1, 0);
// Initialize the count for an empty string
prev[0] = 1;
// Iterate through s and t to calculate counts
for (int i = 1; i <= n; i++) {
/* Iterate in reverse direction to
avoid overwriting values prematurely*/
for (int j = m; j >= 1; j--) {
if (s[i - 1] == t[j - 1]) {
/* If the characters match, consider two options:
either leave one character in s and t or leave
one character in s and continue matching t*/
prev[j] = (prev[j - 1] + prev[j]) % prime;
}
/* No need for an else statement since we
can simply leave the previous count as is*/
}
}
/* The value at prev[m] contains
the count of distinct subsequences*/
return prev[m];
}
};
int main() {
string s1 = "babgbag";
string s2 = "bag";
//Create an instace of Solution class
Solution sol;
// Print the result
cout << "The Count of Distinct Subsequences is " << sol.distinctSubsequences(s1, s2);
return 0;
}
import java.util.Arrays;
class Solution {
private static final int prime = 1000000007;
/* Function to count the number of
distinct subsequences of s in t*/
public int distinctSubsequences(String s, String t) {
int n = s.length();
int m = t.length();
/* Declare an array to store the count of
distinct subsequences for each character in t*/
int[] prev = new int[m + 1];
// Initialize the count for an empty string
prev[0] = 1;
// Iterate through s and t to calculate counts
for (int i = 1; i <= n; i++) {
/* Iterate in reverse direction to
avoid overwriting values prematurely*/
for (int j = m; j >= 1; j--) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
/* If the characters match, consider two options:
either leave one character in s and t or leave
one character in s and continue matching t*/
prev[j] = (prev[j - 1] + prev[j]) % prime;
}
/* No need for an else statement since we
can simply leave the previous count as is*/
}
}
/* The value at prev[m] contains
the count of distinct subsequences*/
return prev[m];
}
public static void main(String[] args) {
String s1 = "babgbag";
String s2 = "bag";
// Create an instance of Solution class
Solution sol = new Solution();
// Print the result
System.out.println("The Count of Distinct Subsequences is " + sol.distinctSubsequences(s1, s2));
}
}
class Solution:
prime = 10**9 + 7
""" Function to count the number of
distinct subsequences of s in t"""
def distinctSubsequences(self, s, t):
n = len(s)
m = len(t)
""" Declare an array to store the count of
distinct subsequences for each character in s"""
prev = [0] * (m + 1)
# Initialize the count for an empty string (base case)
prev[0] = 1
# Iterate through s and t to calculate counts
for i in range(1, n + 1):
""" Iterate in reverse direction to
avoid overwriting values prematurely"""
for j in range(m, 0, -1):
if s[i - 1] == t[j - 1]:
""" If the characters match, consider two options:
either leave one character in s and t or leave
one character in s and continue matching t"""
prev[j] = (prev[j - 1] + prev[j]) % self.prime
""" No need for an else statement since we
can simply leave the previous count as is"""
""" The value at prev[m] contains
the count of distinct subsequences"""
return prev[m]
s1 = "babgbag"
s2 = "bag"
#Create an instance of Solution class
sol = Solution()
#Print the result
print(f"The Count of Distinct Subsequences is {sol.distinctSubsequences(s1, s2)}")
class Solution {
constructor() {
this.prime = 1000000007;
}
/* Function to count the number of
distinct subsequences of s in t*/
distinctSubsequences(s, t) {
let n = s.length;
let m = t.length;
/* Declare an array to store the count of
distinct subsequences for each character in t*/
let prev = Array(m + 1).fill(0);
// Initialize the count for an empty string (base case)
prev[0] = 1;
// Iterate through s and t to calculate counts
for (let i = 1; i <= n; i++) {
/* Iterate in reverse direction to
avoid overwriting values prematurely*/
for (let j = m; j >= 1; j--) {
if (s[i - 1] === t[j - 1]) {
/* If the characters match, consider two options:
either leave one character in s and t or leave
one character in s and continue matching t*/
prev[j] = (prev[j - 1] + prev[j]) % this.prime;
}
/* No need for an else statement since we
can simply leave the previous count as is*/
}
}
/* The value at prev[m] contains
the count of distinct subsequences*/
return prev[m];
}
}
let s1 = "babgbag";
let s2 = "bag";
//Create an instance of Solution class
let sol = new Solution();
//Print the result
console.log("The Count of Distinct Subsequences is " + sol.distinctSubsequences(s1, s2));
Q: Why do we add dp[i-1][j-1] when characters match?
A: This accounts for cases where we include s[i-1] in forming t.
Q: Why do we need to check s[i-1] == t[j-1]?
A: If they match, we can either use or skip s[i-1] while forming t.
Q: How would you reconstruct the actual subsequences instead of just counting them?
A: Maintain a parent pointer in dp[], then backtrack to generate all valid subsequences.
Q: How would this problem change if t contained wildcards (?) that can match any character in s?
A: Modify the recurrence relation to allow universal matches when t[j-1] == '?'.