Try it first — give it 40 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get two strings, s and t. Count the number of distinct subsequences of s that equal t. A subsequence is what's left after deleting zero or more characters, keeping the order. "Distinct" means different sets of positions: two choices of positions count separately even if they spell the same word.
Lengths are up to 1000. The answer is guaranteed to fit in a 32-bit signed integer.
Example: s = "rabbbit", t = "rabbit" → 3. s has three bs, and you keep any two of them:
ra b b _ it
ra b _ b it
ra _ b b itStart with brute force
Try every way to choose len(t) positions from s and check whether they spell t. That's C(m, n) choices. For m = 1000 and n = 500, it's about 10²⁹⁹. Even a smarter recursion, "match or skip each character of s", is O(2ᵐ) without caching.
Building the intuition
This Hard is two Medium ideas stacked together: the two-string DP table from Longest Common Subsequence and the counting recurrence from Climbing Stairs and Unique Paths, where you add the ways instead of taking a max.
Step 1: make one decision. Look at the last character of s. You either
- use it as the last character of
t, which is only possible if they're equal. Then you still need to form the rest oftfrom the rest ofs; or - skip it: form all of
tfrom the rest ofs.
These two cases never overlap: in one the last position is chosen, in the other it isn't. So the total is the sum of the two. No double counting.
Step 2: name the state. The "rest of" pieces are prefixes, so let
dp[i][j] = number of ways to form t[:j] (the first j chars of t) from s[:i]Then:
dp[i][j] = dp[i−1][j] (skip s[i−1])
+ dp[i−1][j−1] if s[i−1] == t[j−1] (use s[i−1] as t[j−1])Step 3: base cases. dp[i][0] = 1 for every i: there's exactly one way to form the empty string, which is to delete everything. And dp[0][j] = 0 for j > 0: an empty s can't form a non-empty t.
Check it with s = "aa", t = "a": dp[1][1] = dp[0][1] + dp[0][0] = 0 + 1 = 1, and dp[2][1] = dp[1][1] + dp[1][0] = 1 + 1 = 2. Two ways: the first a or the second. Correct.
Step 4: shrink to one row. Row i only reads row i − 1. Keep one array dp[0..n]. For each character of s, update dp[j] += dp[j−1] where t[j−1] matches. But go from right to left, so that dp[j−1] is still the old row's value when you read it. It's the same trick as 0/1 knapsack: each character of s may be used at most once per match.
The optimal approach
dp = [1, 0, 0, …, 0](lengthn + 1).- For each character
cins:- for
jfromndown to1: ift[j−1] == c, thendp[j] += dp[j−1].
- for
- Return
dp[n].
The subtle detail: overflow in cells you don't care about. The answer fits in 32 bits, but some cells don't. With s = "a" × 1000 and t = "a" × 500 + "b", the answer is 0, yet dp[250] reaches C(1000, 250), which is far more than 2⁶⁴. Why is the answer still safe? Every cell that feeds into dp[n] adds into it, so it's at most the answer. The huge cells never reach dp[n]. So the final value is right, as long as the language survives the huge cells:
- Python: big integers, no issue.
- Java:
longoverflow just wraps around. No crash, and the wrapped cells never reach the answer. - C++: signed overflow is undefined behaviour, and LeetCode's sanitizer stops the program with a runtime error. Use
unsigned long long, which wraps legally. - JavaScript: huge cells lose precision or become
Infinity. They never feed the answer, and the cells that do stay exact.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def numDistinct(self, s: str, t: str) -> int:
m = len(t)
# dp[j] = number of ways to build t[:j] from the part of s read so far.
# Building the empty prefix has exactly one way: pick nothing.
dp = [1] + [0] * m
for c in s:
# Go right to left so dp[j - 1] is still the value from BEFORE this char,
# the same 0/1-knapsack trick: each char of s is used at most once per match.
for j in range(m, 0, -1):
if t[j - 1] == c:
dp[j] += dp[j - 1] # use c as t[j-1], plus the ways that skip it
return dp[m]class Solution {
public:
int numDistinct(string s, string t) {
int m = t.size();
// dp[j] = number of ways to build t[0..j) from the part of s read so far.
// unsigned: some cells that never reach the answer can pass 2^64; unsigned
// overflow just wraps (signed overflow is undefined, and LeetCode flags it).
vector<unsigned long long> dp(m + 1, 0);
dp[0] = 1; // the empty prefix: one way, pick nothing
for (char c : s) {
// Right to left so dp[j - 1] is still the value from BEFORE this char.
for (int j = m; j >= 1; j--) {
if (t[j - 1] == c) dp[j] += dp[j - 1]; // use c as t[j-1], plus the ways that skip it
}
}
return (int)dp[m];
}
};class Solution {
public int numDistinct(String s, String t) {
int m = t.length();
// dp[j] = number of ways to build t[0..j) from the part of s read so far.
// long: some cells that never reach the answer can still overflow; Java just
// wraps them, and the answer itself is guaranteed to fit in an int.
long[] dp = new long[m + 1];
dp[0] = 1; // the empty prefix: one way, pick nothing
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// Right to left so dp[j - 1] is still the value from BEFORE this char.
for (int j = m; j >= 1; j--) {
if (t.charAt(j - 1) == c) dp[j] += dp[j - 1]; // use c as t[j-1], plus the ways that skip it
}
}
return (int) dp[m];
}
}/**
* @param {string} s
* @param {string} t
* @return {number}
*/
var numDistinct = function (s, t) {
const m = t.length;
// dp[j] = number of ways to build t[0..j) from the part of s read so far.
// Cells that never reach the answer may grow huge and lose precision; every
// cell that does feed the answer is <= the answer, so it stays exact.
const dp = new Array(m + 1).fill(0);
dp[0] = 1; // the empty prefix: one way, pick nothing
for (const c of s) {
// Right to left so dp[j - 1] is still the value from BEFORE this char.
for (let j = m; j >= 1; j--) {
if (t[j - 1] === c) dp[j] += dp[j - 1]; // use c as t[j-1], plus the ways that skip it
}
}
return dp[m];
};Dry run
s = "babgbag", t = "bag". The array is dp[0..3], meaning ways to form "", "b", "ba" and "bag".
| char of s | j = 3 (g) | j = 2 (a) | j = 1 (b) | dp after |
|---|---|---|---|---|
| start | [1, 0, 0, 0] | |||
| b | — | — | += dp[0] → 1 | [1, 1, 0, 0] |
| a | — | += dp[1] → 1 | — | [1, 1, 1, 0] |
| b | — | — | += 1 → 2 | [1, 2, 1, 0] |
| g | += dp[2] → 1 | — | — | [1, 2, 1, 1] |
| b | — | — | += 1 → 3 | [1, 3, 1, 1] |
| a | — | += dp[1] → 1 + 3 = 4 | — | [1, 3, 4, 1] |
| g | += dp[2] → 1 + 4 = 5 | — | — | [1, 3, 4, 5] |
The answer is dp[3] = 5. Look at the second a: it adds 3 to "ba", because each of the three bs before it can pair with it.
Complexity
- Time: O(m·n). For each of the
mcharacters ofs, we scan thenpositions oft. That's 10⁶ steps at the limits. - Space: O(n) for one row. The 2-D table would be O(m·n).
Edge cases and traps
tlonger thans. The answer is 0, and the DP produces it naturally:dp[n]can never get filled.- Left-to-right inner loop. If
jgoes upward,dp[j−1]is already the new value, and one character ofsgets counted twice in the same match. Withs = "a",t = "aa"you'd get 1 instead of 0. - Wrong base case.
dp[0]must be 1, not 0. Otherwise nothing ever gets counted. - Signed overflow in C++.
intorlong longcan overflow in cells that don't matter, and that's still undefined behaviour. Useunsigned long long. - Confusing with LCS. LCS takes a
maxover "skip from s or skip from t". Here you may only skip froms, because every character oftmust be matched. And you add, because you're counting.
Say it in the interview
"For each character of s, I either use it as the next unmatched character of t, or I skip it. The two choices never overlap, so I add them. dp[i][j], the ways to form the first j characters of t from the first i of s, equals dp[i−1][j], plus dp[i−1][j−1] when the characters match. dp[i][0] is 1. Each row only needs the previous one, so I keep one array and loop j from right to left. That's O(m·n) time and O(n) space. Some unused cells can overflow, so in C++ I use unsigned arithmetic."
Follow-ups interviewers ask
- "Return the count modulo 10⁹ + 7 instead." Same DP, taking
% MODafter each addition. Then the overflow question disappears. - "Count distinct subsequences of s itself (all of them, not one target)." (LeetCode 940.) A different recurrence:
dp[i] = 2·dp[i−1] − dp[last[c] − 1], where subtracting removes the repeats created by the previous occurrence of the same character. - "Is t a subsequence of s at all?" That's just two pointers, O(m). This problem is the counting version of that question.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free