Distinct Subsequences

Hard

Topics
StringDynamic Programming

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

srabbbit
trabbit
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

sbabgbag
tbag
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

  1. dp[i][0] = 1 (empty t is matched by exactly one subsequence).
  2. If s[i-1] == t[j-1]: dp[i][j] = dp[i-1][j-1] + dp[i-1][j].
  3. 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] = 1 column 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]
SensAI
Beta
Tap the mic to stop voice mode