hardDynamic ProgrammingStringDynamic Programming

Distinct Subsequences

hardTime: O(m * n)Space: O(m * n)

Signals to notice

count subsequences of s that equal teach character included or skippedoverlapping choices

Brute force first

Generate all subsequences of s and count matches. Exponential in s's length. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

2D DP: dp[i][j] = number of subsequences of s[0.i-1] that equal t[0.j-1]. If s[i-1] == t[j-1]: dp[i][j] = dp[i-1][j-1] (use this match) + dp[i-1][j] (skip it). If not: dp[i][j] = dp[i-1][j]. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

When characters match, you have two valid choices: use the match (consuming both characters) or skip it (only consuming s's character, keeping more flexibility). The total is the sum of both paths. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Forgetting the skip case when characters match — even when s[i] matches t[j], you might find more matches by skipping this particular occurrence of s[i]. The fix is usually to return to the meaning of each move, not just the steps themselves.

Dynamic Programming Pattern