Distinct Subsequences
Problem
Given two strings s and t, count how many different ways you can delete characters from s (possibly none) so that what remains equals t. Two ways are different if the sets of kept positions in s differ, even when the kept characters look identical.
1 <= len(s), len(t) <= 1000- Both strings contain only English letters.
- The answer fits in a 32-bit signed integer.
Examples
s = "googgle", t = "gog"→4. Position sets (0-based): {0,1,3}, {0,1,4}, {0,2,3}, {0,2,4}.s = "catcatcat", t = "cat"→10. Any of the threecatcopies can supply each letter, subject to keeping their relative order.s = "xyz", t = "xyzw"→0.tis longer thans, so nothing can be deleted to reach it.
Hints
- Walk through
sone character at a time and ask how many ways the firsticharacters ofscan produce the firstjcharacters oft. - When
s[i-1] == t[j-1], you may use that character to matcht[j-1], or you may skip it. Both are legitimate and must be added together. dp[i][j] = dp[i-1][j] + (dp[i-1][j-1] if s[i-1] == t[j-1] else 0), withdp[i][0] = 1.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.