TRT
Sign in
hardAdvancedLeetCode#two-string counting DP

Distinct subsequences

Count how many times t appears as a subsequence of s with a two-string counting DP.

The Runtime Theory Team1 min read
Taught inGrids and stringsPro — members onlyTwo-dimensional DP fills a table whose cells depend on their neighbors above and to the left. On grids it counts or optimizes paths; on two strings, a cell compares two prefixes, which is how diff tools, spell checkers and DNA alignment work.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ins = rabbbit, t = rabbit

out3

ins = babgbag, t = bag

out5

ins = abc, t = d

out0

Return the number of distinct subsequences of s that equal t.

Before you code

dp[i][j] counts the ways to form the first j characters of t from the first i of s. The last character of s's prefix is either used for t's last character (only if they match) or not used.

Hints

  1. dp[i][0] = 1: the empty t is formed one way.
  2. dp[i][j] = dp[i-1][j] + (dp[i-1][j-1] if s[i-1] == t[j-1] else 0).
  3. Counts can be large; the problem guarantees they fit in 32 bits.

Production & complexity notes

When solving Distinct subsequences on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Grids and strings to reinforce the underlying pattern.

What it practices

Counting with a two-string table, from Grids and strings.

Not started

Sign in to save your learning progress.

Sign in to save