CodeArchon

hard2-D Dynamic ProgrammingFacebook

Subsequence Appearance Counter

A proofreader counts how many distinct ways a target word appears as a subsequence of a source text.

Given strings s and t, return the number of distinct subsequences of s which equal t.

Choose approach

1
?
?
?
?
?
?
1
1
0
0
0
0
0
row
1
?
?
?
?
?
?
1
?
?
?
?
?
?
1
?
?
?
?
?
?
1
?
?
?
?
?
?
1
?
?
?
?
?
?
1
?
?
?
?
?
?
1/8
Narrationstep 1 of 8

Row 1 filled using s[0] = 'r'.

1def numDistinct(s, t):
2 m, n = len(s), len(t)
3 dp = [[0]*(n+1) for _ in range(m+1)]
4 for i in range(m+1): dp[i][0] = 1
5 for i in range(1, m+1):
6 for j in range(1, n+1):
7 dp[i][j] = dp[i-1][j] + (dp[i-1][j-1] if s[i-1] == t[j-1] else 0)
8 return dp[m][n]
Variables
i=1

How to think about it

  1. Second-level counting on top of LCS structure.
  2. Empty target column always 1 (empty subseq).

Edge cases to catch in interview

  • t empty -> 1.
  • |t| > |s| -> 0.

Examples

Example 15
{"s":"babgbag","t":"bag"}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed