Given two strings s and t, return the number of distinctsubsequences of s which equals t.
The test cases are generated so that the answer fits on a 32-bit signed integer.
Example 1:
Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from s.
rabbbitrabbbitrabbbit
Example 2:
Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from s.
babgbagbabgbagbabgbagbabgbagbabgbag
Problem summary: Given two strings s and t, return the number of distinct subsequences of s which equals t. The test cases are generated so that the answer fits on a 32-bit signed integer.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"rabbbit"
"rabbit"
Example 2
"babgbag"
"bag"
Related Problems
Number of Unique Good Subsequences (number-of-unique-good-subsequences)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #115: Distinct Subsequences
class Solution {
public int numDistinct(String s, String t) {
int m = s.length(), n = t.length();
int[][] f = new int[m + 1][n + 1];
for (int i = 0; i < m + 1; ++i) {
f[i][0] = 1;
}
for (int i = 1; i < m + 1; ++i) {
for (int j = 1; j < n + 1; ++j) {
f[i][j] = f[i - 1][j];
if (s.charAt(i - 1) == t.charAt(j - 1)) {
f[i][j] += f[i - 1][j - 1];
}
}
}
return f[m][n];
}
}
// Accepted solution for LeetCode #115: Distinct Subsequences
func numDistinct(s string, t string) int {
m, n := len(s), len(t)
f := make([][]int, m+1)
for i := range f {
f[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
f[i][0] = 1
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
f[i][j] = f[i-1][j]
if s[i-1] == t[j-1] {
f[i][j] += f[i-1][j-1]
}
}
}
return f[m][n]
}
# Accepted solution for LeetCode #115: Distinct Subsequences
class Solution:
def numDistinct(self, s: str, t: str) -> int:
m, n = len(s), len(t)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
f[i][0] = 1
for i, a in enumerate(s, 1):
for j, b in enumerate(t, 1):
f[i][j] = f[i - 1][j]
if a == b:
f[i][j] += f[i - 1][j - 1]
return f[m][n]
// Accepted solution for LeetCode #115: Distinct Subsequences
impl Solution {
#[allow(dead_code)]
pub fn num_distinct(s: String, t: String) -> i32 {
let n = s.len();
let m = t.len();
let mut dp: Vec<Vec<u64>> = vec![vec![0; m + 1]; n + 1];
// Initialize the dp vector
for i in 0..=n {
dp[i][0] = 1;
}
// Begin the actual dp process
for i in 1..=n {
for j in 1..=m {
dp[i][j] = if s.as_bytes()[i - 1] == t.as_bytes()[j - 1] {
dp[i - 1][j] + dp[i - 1][j - 1]
} else {
dp[i - 1][j]
};
}
}
dp[n][m] as i32
}
}
// Accepted solution for LeetCode #115: Distinct Subsequences
function numDistinct(s: string, t: string): number {
const m = s.length;
const n = t.length;
const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0));
for (let i = 0; i <= m; ++i) {
f[i][0] = 1;
}
for (let i = 1; i <= m; ++i) {
for (let j = 1; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (s[i - 1] === t[j - 1]) {
f[i][j] += f[i - 1][j - 1];
}
}
}
return f[m][n];
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(m × n)
Space
O(m × n)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.