Distinct Subsequences solution explained
Distinct Subsequences counts how many different ways a pattern string can be picked out of a source string by deleting characters, where two ways differ if they use a different set of positions. Fill a table where cell (i, j) counts the ways to form the first j pattern characters from the first i source characters: every cell inherits the count without the current source character, and adds the diagonal count when that character matches the pattern's. An empty pattern can be formed exactly once, which seeds the first column, and the whole thing runs in O(m · n) time with one row of memory.
By Evin JohnPublished 8 min read
The problem, restated
You have a long string, the source, and a short one, the pattern. Cross out letters of the source, without reordering the rest, until what is left spells the pattern exactly. Count how many different choices of crossed-out letters do that. Two ways count as different when they keep a different set of source positions, even if the leftover text looks identical, which it always does.
| Source | Pattern | Ways | Why |
|---|---|---|---|
| aabb | ab | 4 | Either a with either b: 2 x 2 |
| cocoa | coa | 3 | c-o pairs at (1,2), (1,4) and (3,4), each followed by the final a |
| aaaa | aa | 6 | Any 2 of the 4 positions |
| tattoo | tto | 6 | Three ways to pick two t's in order, times two o's |
| cba | abc | 0 | The letters exist but in the wrong order |
| abc | (empty) | 1 | Keep nothing, one way |
What makes it a good interview question
It looks like Longest Common Subsequence, and the table has the same shape, but the question is counting rather than optimizing. That changes the recurrence from a max to a sum and changes the base cases in a way that trips people up. Interviewers use it to see whether you can define the cell precisely, explain both cases of the recurrence from the meaning of the cell, and notice that the answers can become enormous.
Follow-ups
- Use less memory. One row of length n + 1, updated from right to left.
- The count overflows. Some versions promise the answer fits in 32 bits; others ask for it modulo a large prime. Python integers never overflow; in JavaScript switch to BigInt or apply the modulus at every addition.
- Is the pattern a subsequence at all? That is a yes-or-no question answered by one pass with two pointers, no table needed.
- Count distinct subsequences of a single string. A different problem: each new character doubles the count, minus the count from just before that character's previous occurrence.
Brute force
Choose n positions out of the m source positions in increasing order and check whether they spell the pattern. There are m choose n such choices, which explodes for any realistic size. A recursive version walks the source and, at each character, either uses it for the next pattern character (if it matches) or skips it. That recursion only depends on two numbers, how far along the source you are and how far along the pattern, so it has at most (m + 1) · (n + 1) distinct states.
def count_ways_slow(s, t, i=0, j=0):
if j == len(t):
return 1 # the whole pattern is matched
if i == len(s):
return 0 # source used up first
ways = count_ways_slow(s, t, i + 1, j) # skip s[i]
if s[i] == t[j]:
ways += count_ways_slow(s, t, i + 1, j + 1) # use s[i]
return waysThe table
Let ways[i][j] be the number of ways to form the first j characters of the pattern from the first i characters of the source. Look at the last source character, s[i - 1]. Every way that does not use it is already counted in ways[i - 1][j]. If it equals t[j - 1], it can also serve as the last pattern character, and the ways to form the rest come from ways[i - 1][j - 1]. Add the two. The first column is all 1s, since an empty pattern is formed once from any prefix, and the rest of the first row is 0.
| empty | c | o | a | |
|---|---|---|---|---|
| empty | 1 | 0 | 0 | 0 |
| c | 1 | 1 | 0 | 0 |
| o | 1 | 1 | 1 | 0 |
| c | 1 | 2 | 1 | 0 |
| o | 1 | 2 | 3 | 0 |
| a | 1 | 2 | 3 | 3 |
Read the o column. After the first o there is one c-o pair. The second c adds a new way to form c but no new c-o pair yet. The second o can follow either c, adding 2 to the 1 that already existed, for 3. The final a extends each of those three pairs, and the answer is 3.
def count_ways_table(s, t):
m, n = len(s), len(t)
ways = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
ways[i][0] = 1 # the empty pattern
for i in range(1, m + 1):
for j in range(1, n + 1):
ways[i][j] = ways[i - 1][j] # leave s[i - 1] out
if s[i - 1] == t[j - 1]:
ways[i][j] += ways[i - 1][j - 1] # use it for t[j - 1]
return ways[m][n]One row, updated right to left
Each new row reads only the previous row, at the same column and one column to the left. If you overwrite a single row from left to right, the left neighbor has already been updated by the time you need its old value, and a source character could be used twice. Going from right to left avoids that, because column j - 1 still holds the previous row's value when column j is computed. This is the same reason a 0/1 knapsack loop runs downward.
def count_ways(s, t):
row = [1] + [0] * len(t) # row[j]: ways to form t[:j] so far
for ch in s:
for j in range(len(t), 0, -1): # right to left
if ch == t[j - 1]:
row[j] += row[j - 1]
return row[len(t)]function numDistinct(s, t) {
const row = new Array(t.length + 1).fill(0n);
row[0] = 1n;
for (const ch of s) {
for (let j = t.length; j >= 1; j--) {
if (ch === t[j - 1]) row[j] += row[j - 1];
}
}
return row[t.length];
}Counts grow very fast. A source of fifty copies of one letter and a pattern of twenty-five copies already gives fifty choose twenty-five, above 10^14, and slightly larger inputs pass 2^53, where ordinary JavaScript numbers stop being exact. BigInt avoids the problem at some speed cost. If the interviewer gives a modulus, take it after each addition and keep plain numbers.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Choose positions and check | O(C(m, n) · n) | O(n) |
| Skip-or-use recursion, no cache | Exponential | O(m) stack |
| Memoized recursion | O(m · n) | O(m · n) |
| Full table | O(m · n) | O(m · n) |
| One row, right to left | O(m · n) | O(n) |
Edge cases
- Empty pattern: 1, whatever the source.
- Empty source with a non-empty pattern: 0.
- Pattern longer than the source: 0, and you can return early.
- Source made of one repeated letter: the answer is a binomial coefficient, a good check for your table.
- Letters present but in the wrong order: 0.
Common mistakes
- Setting the first column to 0, which makes every count 0.
- Using a max instead of a sum, copied from the LCS recurrence.
- On a match, adding only the diagonal and dropping the skip case.
- Updating the single row left to right, so one source character fills two pattern positions.
- Ignoring overflow when the source is long and highly repetitive.
How to explain it out loud
Fictional example
- Candidate
- I will count ways of i, j: how many ways the first i source letters can form the first j pattern letters. With an empty pattern there is exactly one way, keep nothing, so that column is all ones.
- Candidate
- For the next source letter I can always leave it out, which gives the cell above. If it matches the current pattern letter I can also use it, which adds the diagonal.
- Candidate
- That is m times n. One row is enough if I go right to left so I read the old diagonal. The counts get big quickly, so in a fixed-width language I would ask about overflow or a modulus.
Related problems
Longest Common Subsequence uses the same grid with a max instead of a sum, and Edit Distance uses it with a min over three operations. For a different kind of DP, Best Time to Buy and Sell Stock with Cooldown tracks a few states per day instead of a grid of prefixes.
Practicing with Natively
Counting problems go wrong in the base cases, so practice saying them before you write any loop. Natively on Mac or Windows can read a problem like this from a screenshot during a practice session and suggest a way to set up the table, worth comparing with your own after you try. It also keeps a transcript of the mock, so you can check whether you raised overflow without being asked. See the AI interview assistant.
Questions people ask
How do you solve Distinct Subsequences?
Let ways[i][j] count the ways the first i source characters form the first j pattern characters. Each cell copies the cell above, and adds the diagonal when the source character matches the pattern character. The first column is all 1s.
Why is the first column of the Distinct Subsequences table 1?
An empty pattern can be formed from any prefix of the source in exactly one way: by keeping no characters. Without that 1 nothing would ever be counted.
What is the time and space complexity of Distinct Subsequences?
O(m · n) time for a source of length m and a pattern of length n. The full table uses O(m · n) memory; one row updated from right to left uses O(n).
How is Distinct Subsequences different from Longest Common Subsequence?
Both fill a grid over two strings, but LCS takes a maximum to find the longest shared subsequence, while Distinct Subsequences adds counts to find how many ways one string appears inside the other.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
