Distinct Subsequences (LeetCode 115): Solution and Explanation
Given strings s and t, count the number of distinct ways to delete characters from s so that what remains is exactly t. Two ways are different if they keep a different set of positions from s, even when the resulting strings look the same.
Watch it run step by step
Try your own input and write the code →Intuition
Brute force would try every subset of positions in s and compare, which is 2^m possibilities. A recursive count is better: match s and t from the front, and at each character of s decide whether to use it for the next character of t or skip it. That recursion repeats the same pairs of prefixes many times, which is a strong hint for dynamic programming.
Define dp[i][j] as the number of ways the first i characters of s can produce the first j characters of t. Consider the last character s[i-1]. You can always ignore it, which contributes dp[i-1][j] ways. If it equals t[j-1], you can also use it to match that last character of t, which contributes dp[i-1][j-1] ways. The two choices never overlap, so you add them.
The base cases pin everything down. An empty t can be produced from any prefix of s in exactly one way (delete everything), so the first column is all 1. A non-empty t from an empty s is impossible, so the rest of the first row is 0.
Approach: 2D dynamic programming on prefixes
- Let
m = len(s)andn = len(t), and build an(m + 1)by(n + 1)table of zeros. - Set
dp[i][0] = 1for everyi, since the empty string is a subsequence of every prefix. - For each
ifrom 1 to m and eachjfrom 1 to n, start withdp[i][j] = dp[i-1][j], the count that skipss[i-1]. - If
s[i-1] == t[j-1], adddp[i-1][j-1], the count that usess[i-1]as the match fort[j-1]. - Return
dp[m][n].
Step-by-step example
s = "babgbag", t = "bag"
- Rows below list
dp[i][0..3]. Row 0 is[1, 0, 0, 0]. - After
b:[1, 1, 0, 0]. Aftera:[1, 1, 1, 0]. After the secondb:[1, 2, 1, 0], since there are now twobs to start with. - After
g:[1, 2, 1, 1], the first full match. After the thirdb:[1, 3, 1, 1]. - After the second
a:dp[6][2] = 1 + dp[5][1] = 1 + 3 = 4, so the row is[1, 3, 4, 1]. - After the final
g:dp[7][3] = dp[6][3] + dp[6][2] = 1 + 4 = 5. The answer is 5.
Code: Python, Java, C++
1class Solution:
2 def numDistinct(self, s: str, t: str) -> int:
3 m, n = len(s), len(t)
4 dp = [[0] * (n + 1) for _ in range(m + 1)]
5
6 # Empty t is a subsequence of any prefix of s
7 for i in range(m + 1):
8 dp[i][0] = 1
9
10 for i in range(1, m + 1):
11 for j in range(1, n + 1):
12 dp[i][j] = dp[i - 1][j] # Skip s[i-1]
13 if s[i - 1] == t[j - 1]:
14 dp[i][j] += dp[i - 1][j - 1] # Use s[i-1]
15
16 return dp[m][n]1class Solution {
2 public int numDistinct(String s, String t) {
3 int m = s.length(), n = t.length();
4 int[][] dp = new int[m + 1][n + 1];
5
6 // Empty t is a subsequence of any prefix of s
7 for (int i = 0; i <= m; i++) {
8 dp[i][0] = 1;
9 }
10
11 for (int i = 1; i <= m; i++) {
12 for (int j = 1; j <= n; j++) {
13 dp[i][j] = dp[i - 1][j]; // Skip s[i-1]
14 if (s.charAt(i - 1) == t.charAt(j - 1)) {
15 dp[i][j] += dp[i - 1][j - 1]; // Use s[i-1]
16 }
17 }
18 }
19
20 return dp[m][n];
21 }
22}1class Solution {
2public:
3 int numDistinct(string s, string t) {
4 int m = s.size(), n = t.size();
5 vector<vector<unsigned long long>> dp(m + 1, vector<unsigned long long>(n + 1, 0));
6
7 // Empty t is a subsequence of any prefix of s
8 for (int i = 0; i <= m; i++) {
9 dp[i][0] = 1;
10 }
11
12 for (int i = 1; i <= m; i++) {
13 for (int j = 1; j <= n; j++) {
14 dp[i][j] = dp[i - 1][j]; // Skip s[i-1]
15 if (s[i - 1] == t[j - 1]) {
16 dp[i][j] += dp[i - 1][j - 1]; // Use s[i-1]
17 }
18 }
19 }
20
21 return dp[m][n];
22 }
23};Time and space complexity
O(m × n)
Every cell of the table is filled once in constant time.
O(m × n)
The table has (m + 1) × (n + 1) entries. It can be reduced to O(n) by keeping a single row and iterating j from right to left.
Other approaches
Memoized recursion (time O(m × n), space O(m × n))
Recurse on indices (i, j) from the front, returning 1 when t is exhausted and 0 when s runs out, and cache results. It is the same recurrence top down.
One-dimensional DP (time O(m × n), space O(n))
Keep one array of length n + 1 and update j from n down to 1, so dp[j-1] still holds the previous row's value when it is read.
Common mistakes
- Setting only
dp[0][0] = 1instead of the whole first column. Every prefix ofscan form the empty string, and missing those 1s zeros out the whole table. - Using
dp[i-1][j-1]alone when characters match, forgetting that you may also skip a matching character. That undercounts whenevershas repeated letters. - Iterating
jupward in the one-row version, which overwritesdp[j-1]before it is used and double counts. - Ignoring overflow in Java or C++. Intermediate counts can exceed 32 bits even when the final answer fits, so use a wider type or rely on the problem's guarantee carefully.
Frequently asked questions
What does dp[i][j] mean in distinct subsequences?
It is the number of ways the first i characters of s can form the first j characters of t as a subsequence. The answer is the cell for the full lengths.
Why is dp[i][0] equal to 1?
There is exactly one way to form an empty string from any prefix: delete every character. That base case is what lets a complete match count as one way.
What is the time complexity of distinct subsequences?
O(m × n), because each pair of prefix lengths is computed once with a constant amount of work.
Can distinct subsequences use O(n) space?
Yes. Each row only depends on the row above, so a single array updated from right to left works.