hardDynamic ProgrammingStringDynamic Programming

Distinct Subsequences

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

Recognize the pattern

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

Brute force idea

The naive version of Distinct Subsequences sounds like this: 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.

Better approach

The real unlock in Distinct Subsequences comes when you notice this: 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.

Key invariant

The compass for Distinct Subsequences is this: 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.

Watch out for

One easy way to drift off course in Distinct Subsequences is this: 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