Distinct Subsequences
Hard
Topics
Given two strings s and t, return the number of distinct subsequences of s that equal t. The answer fits in a 32-bit integer.
Example 1
s
t
one way to spell t
Deleting characters from
s without reordering the rest must leave rabbit. The shading marks one way to do that; the answer counts how many distinct ways exist, 3 here. Two ways differ when they delete different positions, even if the surviving letters look the same.Rows are the two strings; shaded cells in s are one way of spelling t.
Input: s = "rabbbit", t = "rabbit" Output: 3
Example 2
s
t
one way to spell t
Input: s = "babgbag", t = "bag" Output: 5
Constraints
- 1 <= s.length, t.length <= 1000
- Inputs consist of English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
dp[i][j] counts how many subsequences of the first i chars of s equal the first j chars of t. When the current chars match you may either use s[i-1] to cover t[j-1] or skip it; when they differ you can only skip it.
Approach
- dp[i][0] = 1 (empty t is matched by exactly one subsequence).
- If s[i-1] == t[j-1]: dp[i][j] = dp[i-1][j-1] + dp[i-1][j].
- Else dp[i][j] = dp[i-1][j].
Dry Run
s = "rabbbit" t = "rabbit"
dp[i][j] = how many subsequences of s[:i] spell t[:j].
Column j=0 is seeded to 1 on every row: there is exactly one way to spell "",
by taking nothing. Without that column the whole table stays 0.
"" r a b b i t
i=0 "" 1 0 0 0 0 0 0
i=1 r 1 1 0 0 0 0 0
i=2 a 1 1 1 0 0 0 0
i=3 b 1 1 1 1 0 0 0
i=4 b 1 1 1 2 1 0 0
i=5 b 1 1 1 3 3 0 0
i=6 i 1 1 1 3 3 3 0
i=7 t 1 1 1 3 3 3 3
answer dp[7][6] = 3
Follow the first 'b' column (j=3) down the rows: 1, then 2, then 3, one for each of
the three b's in s. That growth is the match branch adding BOTH options rather than
choosing between them -- dp[i-1][j-1] spends s[i-1] on t[j-1], dp[i-1][j] skips it.
Row i=4 is where the second target b first becomes reachable at all (j=4 goes
0 -> 1), because you need two of s's b's before you can cover "rabb".
Rows i=6 and i=7 each advance one cell only, since 'i' and 't' occur once.
The answer 3 is exactly "which of the three b's do you leave out": the winning
index sets are (0,1,2,3,5,6), (0,1,2,4,5,6) and (0,1,3,4,5,6).Complexity
- Time — O(m*n): fill the table.
- Space — O(m*n): the DP grid (reducible to O(n)).
Common Pitfalls
- The
dp[i][0] = 1column is the base case that makes the whole table non-zero: there is exactly one way to form the empty target, by taking nothing. Skip it and every answer is 0. - When the characters match you add both branches -- use this character, or skip it -- rather than choosing one. That addition is what makes this a count rather than a yes/no match.
Full Solution — all languages
class Solution:
def numDistinct(self, s, t):
m,n=len(s),len(t)
dp=[[0]*(n+1) for _ in range(m+1)]
for i in range(m+1): dp[i][0]=1
for i in range(1,m+1):
for j in range(1,n+1):
dp[i][j]=dp[i-1][j]+(dp[i-1][j-1] if s[i-1]==t[j-1] else 0)
return dp[m][n]import java.util.*;
class Solution {
public int numDistinct(String s, String t) {
int m=s.length(),n=t.length();
long[][] dp=new long[m+1][n+1];
for(int i=0;i<=m;i++)dp[i][0]=1;
for(int i=1;i<=m;i++)for(int j=1;j<=n;j++) {
dp[i][j]=dp[i-1][j];
if(s.charAt(i-1)==t.charAt(j-1))dp[i][j]+=dp[i-1][j-1];
}
return (int)dp[m][n];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int numDistinct(string s, string t) {
int m=s.size(),n=t.size();
vector<vector<long long>> dp(m+1,vector<long long>(n+1,0));
for(int i=0;i<=m;i++)dp[i][0]=1;
for(int i=1;i<=m;i++)for(int j=1;j<=n;j++) {
dp[i][j]=dp[i-1][j];
if(s[i-1]==t[j-1])dp[i][j]+=dp[i-1][j-1];
}
return (int)dp[m][n];
}
};/**
* @param {string} s
* @param {string} t
* @return {number}
*/ var numDistinct = function(s, t) {
const m=s.length,n=t.length,dp=[];
for(let i=0;i<=m;i++) {
dp.push(new Array(n+1).fill(0));
dp[i][0]=1;
}
for(let i=1;i<=m;i++)for(let j=1;j<=n;j++) {
dp[i][j]=dp[i-1][j];
if(s[i-1]===t[j-1])dp[i][j]+=dp[i-1][j-1];
}
return dp[m][n];
};