15% off all plans & roadmaps Use code

See plans

Distinct Subsequences

Updated

TL;DR: Count the index selections in `s` that spell `t`. Track, for every prefix of `t`, how many ways the characters of `s` seen so far can form it, and update a 1D array from right to left.

Problem

You are given two strings s and t. A subsequence is built by deleting zero or more characters from a string while keeping the remaining characters in their original order. The kept characters do not have to be adjacent.

Count the ways to pick indices in s so that the characters at those indices, read in increasing index order, spell t. Two picks are different when they use different indices, even if the resulting text is the same. Return the number of distinct subsequences of s that equal t.

If t is empty there is exactly one such subsequence: pick nothing. If s is empty and t is not, the answer is 0.

Example 1

Input: s = "abac", t = "ac"
Output: 2
Explanation: The target can start with the a at index 0 or the a at index 2, and then end with the c at index 3.

Example 2

Input: s = "aaaaa", t = "aaa"
Output: 10
Explanation: Any three of the five positions can be chosen, which gives 5 choose 3 = 10 index selections.

Example 3

Input: s = "cabana", t = "can"
Output: 2
Explanation: The c must come first and the n is near the end. Either of the two a characters before the n can sit between them.

Constraints

  • 1 <= s.length <= 1000
  • 1 <= t.length <= 1000
  • s and t contain only lowercase English letters.
  • The answer fits in a 32-bit signed integer.

Constraints that matter

  • s.length and t.length up to 1000 means an O(m * n) table has at most about one million cells, which is fast. Anything exponential in m is not.
  • A plain include-or-skip recursion can make about 2^m calls when m is 1000. That rules out brute force and pushes you to cache repeated (i, j) states.
  • The answer fits in a signed 32-bit integer, but intermediate table values often do not. For example, with s as 1000 copies of a and t as 500 copies, some cells hold a count near C(1000, 500). Wrap around or use a wider type in languages with fixed-size integers.
  • Only lowercase letters appear, so you never need to handle case or Unicode. The problem is purely about matching positions.
  • Recursion depth equals s.length, so up to about 1000 frames. That is fine in Java, C++, C# and Go but exceeds the default Python limit, so a recursive Python solution must raise it.

View on LeetCode

Hints

Hint 1

This is a Dynamic Programming problem on two string prefixes, the same grid shape you use for Longest Common Subsequence.

Hint 2

Walk through s one character at a time with two pointers, i into s and j into t.

Solution

Intuition

This is a Dynamic Programming problem on two string prefixes, the same grid shape you use for Longest Common Subsequence. The value in each cell is a count, not a length. The signal is the phrase "number of ways" combined with two strings where order matters.

Picture a row of jars, one per prefix of t, where the first jar starts with one token and the rest are empty. Each character of s sweeps the jars from the far end toward the front, and on a match it pours the count from jar j-1 into jar j, so the jar at the end ends up holding the total.

Look at the last character of the prefix of s you are considering. If it does not equal the last character of the target prefix, it cannot be the final pick, so every way comes from the shorter s prefix. If it does match, you have two disjoint groups of ways. Either you skip this character, or you use it as the last pick and the rest of the target must come from the shorter s prefix.

That gives the recurrence dp[i][j] = dp[i-1][j] + (s[i-1] == t[j-1] ? dp[i-1][j-1] : 0). The base case is dp[i][0] = 1, because the empty target has one way: choose nothing. Each cell reads only the row above it, so a single array is enough if you update it in the right order.

The skip branch and the use branch never overlap, because they differ on whether index i-1 is selected. That is why you can add them without double counting. It is also why equal letters count separately: different indices give different selections.

Watch the pattern animation

Worked example

Input: s = "cabana", t = "can"
Output: 2
Explanation: The string cabana has indices c0 a1 b2 a3 n4 a5. The c at index 0 is the only choice for c, and the n at index 4 is the only choice for n. The middle a can be index 1 or index 3, so the two selections are (0, 1, 4) and (0, 3, 4). The a at index 5 comes after the n, so it cannot be used.

Approach 1: Brute force recursion

Walk through s one character at a time with two pointers, i into s and j into t. At each step you may skip s[i]. If s[i] == t[j], you may also use it and advance both pointers. When j reaches the end of t, you have found one valid selection and return 1. When i reaches the end of s first, that branch returns 0.

This is the definition of the problem written as code. It tries every include-or-skip choice, so it is correct, but it is also the slowest option.

Steps

  1. Define count(i, j) as the number of ways to form t[j:] from s[i:].
  2. If j == len(t), return 1, because the target is fully matched.
  3. If i == len(s), return 0, because the source ran out with target left over.
  4. Set ways = count(i + 1, j) for the skip choice.
  5. If s[i] == t[j], add count(i + 1, j + 1) for the use choice.
  6. Return ways. The answer is count(0, 0).

Dry run

Trace count(i, j) on s = "cabana", t = "can".

  • count(0,0): c matches c. Use gives count(1,1). Skip gives count(1,0), which scans the rest of s for a c, never finds one, and returns 0.
  • count(1,1): a matches a. Use gives count(2,2). Skip gives count(2,1).
  • count(2,2): b is not n, so it goes to count(3,2), then count(4,2). There n matches: use gives count(5,3) = 1, and skip gives count(5,2) = 0. So count(4,2) = 1 and count(2,2) = 1.
  • count(2,1): b is not a, so it goes to count(3,1). There a matches: use gives count(4,2) = 1 (computed again), and skip gives count(4,1) = 0. So count(2,1) = 1.
  • count(1,1) = 1 + 1 = 2, and count(0,0) = 2 + 0 = 2.

Notice that count(4,2) was computed twice. On larger inputs this repeated work explodes.

Complexity

TimeO(2^m)
SpaceO(m)

Let m be the length of s. Each call either stops or advances i by one, so the recursion depth is at most m and the stack uses O(m) space. Each call makes at most two child calls, so the call tree has at most 2^(m+1) nodes. That bound is loose in practice, but the worst case, such as s and t both made of one repeated letter, grows exponentially.

PythonTested in our runner

import sys
from typing import List, Optional

class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        sys.setrecursionlimit(10000)
        m, n = len(s), len(t)

        def count(i: int, j: int) -> int:
            if j == n:
                return 1
            if i == m:
                return 0
            ways = count(i + 1, j)  # skip s[i]
            if s[i] == t[j]:
                ways += count(i + 1, j + 1)  # use s[i]
            return ways

        return count(0, 0)
2D Array (Longest Common Subsequence - LCS) pattern infographic for Distinct Subsequences

Solution pattern

2D Array (Longest Common Subsequence - LCS)

Part of Dynamic Programming (DP) Patterns

Approach 2: Top-down memoization2D Array (Longest Common Subsequence - LCS)

What's slow: the brute force reaches the same pair (i, j) through many different paths, and it recomputes the whole subtree every time. In the trace above, count(4,2) was evaluated twice for a six-letter string. With 1000 letters the repeats are astronomical.

The insight that fixes it: count(i, j) depends only on i and j, not on how you got there. Store each result the first time you compute it and return the stored value afterwards. There are only (m + 1) * (n + 1) distinct states, so the work drops from exponential to about one million operations.

Steps

  1. Create a table memo of size (m + 1) by (n + 1), filled with a sentinel such as -1 meaning not computed.
  2. Write the same count(i, j) function as the brute force, with the same two base cases.
  3. At the top of count, return memo[i][j] if it is not the sentinel.
  4. Compute ways from the skip branch, and add the use branch when s[i] == t[j].
  5. Store ways in memo[i][j] before returning it.
  6. Return count(0, 0).

Dry run

Run the memoized version on s = "cabana", t = "can". The first descent is the same as in the brute force.

  • count(0,0) calls count(1,1) and count(1,0). The skip branch count(1,0) walks count(2,0) through count(6,0), all of which return 0, and caches each one.
  • count(1,1) calls count(2,2) and count(2,1).
  • count(2,2) reaches count(4,2), computes 1, and stores memo[4][2] = 1. Then memo[3][2] = 1 and memo[2][2] = 1.
  • count(2,1) reaches count(3,1), which asks for count(4,2). This time it is a cache hit and returns 1 immediately, with no further recursion.
  • memo[3][1] = 1, memo[2][1] = 1, memo[1][1] = 1 + 1 = 2, and count(0,0) = 2.

The repeated count(4,2) call now costs one lookup.

Complexity

TimeO(m * n)
SpaceO(m * n)

Let m be the length of s and n the length of t. There are (m + 1) * (n + 1) distinct (i, j) pairs, and each is computed once with a constant amount of work, so time is O(m * n). The memo table holds one value per pair, which is O(m * n) space. The recursion adds a stack of depth at most m, which is smaller than the table.

PythonTested in our runner

import sys
from functools import lru_cache
from typing import List, Optional

class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        sys.setrecursionlimit(10000)
        m, n = len(s), len(t)

        @lru_cache(maxsize=None)
        def count(i: int, j: int) -> int:
            if j == n:
                return 1
            if i == m:
                return 0
            ways = count(i + 1, j)  # skip s[i]
            if s[i] == t[j]:
                ways += count(i + 1, j + 1)  # use s[i]
            return ways

        return count(0, 0)

Approach 3: Bottom-up 1D DPOptimal

What's slow: memoization still stores a full table, and it pays for recursion on every state. Each row of the table depends only on the row before it, so keeping all rows wastes memory.

The insight that fixes it: flip the direction and keep one array dp of length n + 1, where dp[j] is the number of ways the characters of s seen so far can form t[:j]. Start with dp[0] = 1 and all other entries 0. For each character c of s, scan j from n down to 1, and when c == t[j-1] add dp[j-1] to dp[j].

The right-to-left order matters. dp[j] reads dp[j-1], and you need the value from before this character was processed. Going downward means dp[j-1] has not been touched yet. Going upward would let one character of s extend a match it just created, so it would be used twice.

Why it is correct. After processing some prefix of s, dp[j] equals the number of index selections in that prefix that spell t[:j]. When a character is handled, the sweep from right to left means dp[j-1] still holds its value from before that character. So each selection that ends at this character is counted once and never reused for the same character.

Steps

  1. Create dp of length len(t) + 1 filled with 0, then set dp[0] = 1.
  2. Loop over each character c in s from left to right.
  3. For each c, loop j from len(t) down to 1.
  4. If c == t[j - 1], do dp[j] += dp[j - 1].
  5. Leave dp[j] alone when the characters differ.
  6. After the last character of s, return dp[len(t)].

Dry run

Each row below is one character of s = "cabana" with t = "can". The array dp has indices 0 to 3 and starts as [1, 0, 0, 0]. The scan goes j = 3, 2, 1.

StepChar of sMatches found (j: t[j-1])Updatedp after
0startnonenone[1, 0, 0, 0]
1cj=1 (c)dp[1] += dp[0] gives 1[1, 1, 0, 0]
2aj=2 (a)dp[2] += dp[1] gives 1[1, 1, 1, 0]
3bnonenone[1, 1, 1, 0]
4aj=2 (a)dp[2] += dp[1] gives 2[1, 1, 2, 0]
5nj=3 (n)dp[3] += dp[2] gives 2[1, 1, 2, 2]
6aj=2 (a)dp[2] += dp[1] gives 3[1, 1, 3, 2]

After step 6 the answer is dp[3] = 2, which matches the expected output. The last a raised dp[2] to 3, but it came after the n, so it never reached dp[3]. That is correct, since an a after the n cannot sit between c and n.

Complexity

TimeO(m * n)
SpaceO(n)

Let m be the length of s and n the length of t. The outer loop runs m times, and the inner loop runs n times per iteration with one comparison and at most one addition, so time is O(m * n), about one million steps at the limits. The only storage is the dp array of n + 1 entries, so space is O(n) plus a few scalars.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        n = len(t)
        # dp[j] = ways to form t[:j] from the part of s processed so far
        dp = [0] * (n + 1)
        dp[0] = 1
        for c in s:
            # go right to left so dp[j - 1] still holds the old value
            for j in range(n, 0, -1):
                if c == t[j - 1]:
                    dp[j] += dp[j - 1]
        return dp[n]

Common mistakes

  • Looping j from 1 up to len(t) in the 1D version. dp[j - 1] then already includes the current character, so one index of s is counted twice. Iterate j from len(t) down to 1.
  • Starting with dp[0] = 0. Every nonempty prefix gets its first match from dp[0], so the whole array stays 0. Set dp[0] = 1 for the empty target.
  • Writing dp[j] = dp[j - 1] on a match instead of dp[j] += dp[j - 1]. That throws away the skip branch, which is every way that does not use the current character. Always add.
  • Using int for the memo table in C++ with signed arithmetic. Intermediate counts like C(1000, 500) overflow, and signed overflow is undefined behavior. Use unsigned int, or mask a long long, so the low 32 bits stay exact.
  • Returning early when the characters differ in the recursive version without keeping the skip call. The line return count(i + 1, j + 1) if s[i] == t[j] drops the skip branch. Compute count(i + 1, j) first, then add the use branch on a match.
  • Treating the problem as counting distinct strings. Selections that use different indices are different even if they spell the same text, so never deduplicate by value. Example 2 has answer 10, not 1.

Edge cases

  • s = "a", t = "a" returns 1. One character matches one character.
  • t longer than s, such as s = "ab", t = "abc", returns 0. The target cannot fit, and the table naturally gives 0.
  • All equal letters, s = "aaaaa", t = "aaa", returns 10. This checks that skip and use are both added.
  • No match at all, s = "bbb", t = "a", returns 0. Every dp[j] for j > 0 stays 0.
  • Wrong order of letters, s = "ba", t = "ab", returns 0. The letters exist but not in the needed order.
  • Maximum size with one repeated letter, s of 1000 a and t of 1000 a, returns 1. Intermediate cells are enormous, so this tests overflow handling.

Follow-ups interviewers ask

Can you reduce the extra space below O(m * n)?
Yes. Each row of the 2D table depends only on the previous row, so keep one array of length n + 1 and update it from right to left. That gives O(n) extra space with the same O(m * n) time. The right-to-left order replaces the need for a separate previous-row copy.
What if the answer did not fit in 32 bits and you had to return it modulo 10^9 + 7?
Apply the modulus after every addition, dp[j] = (dp[j] + dp[j - 1]) % MOD. In Java, C++ and C# use a 64-bit type for the sum so it cannot overflow before the reduction. Because the recurrence only adds, taking the modulus at each step gives the same result as at the end.
What changes if you count distinct resulting strings instead of distinct index selections?
With a fixed target t the answer collapses to 1 if t is a subsequence of s and 0 otherwise. A two-pointer scan decides that in O(m) time. The index-counting DP is needed only because different index choices count separately. Counting distinct strings is a different problem, as in Distinct Subsequences II, where the target is not fixed.

Distinct Subsequences FAQ

What does "distinct subsequences" mean in LeetCode 115?

It means different index selections in s whose characters, kept in order, spell t. Two selections are different when they use at least one different index. For s = "aaaaa" and t = "aaa", all ten ways to choose three positions count separately.

What is the time complexity of Distinct Subsequences?

The DP runs in O(m * n), where m is the length of s and n is the length of t. The 1D version uses O(n) space and the memoized version uses O(m * n). The plain recursion without caching takes exponential time, about O(2^m) in the worst case.

Why use dynamic programming for Distinct Subsequences?

The count for a pair of prefixes depends only on smaller prefix pairs, and the same pairs appear again and again in the recursion. Dynamic programming stores each pair once and reuses it. That turns exponential work into about one million operations at the size limits.

How do I find all subsequences of a string, and why not do that here?

You can enumerate them with include-or-skip recursion or with bitmasks, which gives 2^m subsequences for a string of length m. That is only practical for small strings. Here you only need the count of those equal to t, so you count with a table instead of listing.

Can Distinct Subsequences be solved in O(1) extra space?

Not with this recurrence. You must remember a count for each prefix of t, which takes O(n) space. I do not know of a constant-space method, and the 1D array is the standard minimum.

Is Distinct Subsequences the hardest LeetCode problem?

No. It is labeled Hard, but the code is short once you see the recurrence. Difficulty on LeetCode mostly reflects how hard it is to find the state and transition, not the length of the code.

Why does integer overflow matter if the answer fits in 32 bits?

Only the final answer is guaranteed to fit. Cells for shorter prefixes can hold far larger counts. Because the recurrence only adds, wrapping on overflow keeps the low bits exact. The true answer is below 2^31, so the wrapped final value equals it. In JavaScript, reduce modulo 2^32 after each addition, since numbers above 2^53 lose precision.

Asked at

See which companies ask this — Pro

Practise it