Distinct Subsequences (LeetCode 115): Solution and Explanation

Hard
String
Dynamic Programming

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Let m = len(s) and n = len(t), and build an (m + 1) by (n + 1) table of zeros.
  2. Set dp[i][0] = 1 for every i, since the empty string is a subsequence of every prefix.
  3. For each i from 1 to m and each j from 1 to n, start with dp[i][j] = dp[i-1][j], the count that skips s[i-1].
  4. If s[i-1] == t[j-1], add dp[i-1][j-1], the count that uses s[i-1] as the match for t[j-1].
  5. Return dp[m][n].

Step-by-step example

s = "babgbag", t = "bag"
  1. Rows below list dp[i][0..3]. Row 0 is [1, 0, 0, 0].
  2. After b: [1, 1, 0, 0]. After a: [1, 1, 1, 0]. After the second b: [1, 2, 1, 0], since there are now two bs to start with.
  3. After g: [1, 2, 1, 1], the first full match. After the third b: [1, 3, 1, 1].
  4. After the second a: dp[6][2] = 1 + dp[5][1] = 1 + 3 = 4, so the row is [1, 3, 4, 1].
  5. 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]

Time and space complexity

Time

O(m × n)

Every cell of the table is filled once in constant time.

Space

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] = 1 instead of the whole first column. Every prefix of s can 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 whenever s has repeated letters.
  • Iterating j upward in the one-row version, which overwrites dp[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.