HardNo. 0115

Distinct Subsequences — LeetCode 115 Python Solution

Topics
String, Dynamic Programming
On a study list
NeetCode 150
Reading time
2 min

The problem

Given two strings s and t, return the number of distinct subsequences of s which equals t. The test cases are generated so that the answer fits on a 32-bit signed integer.

Example

Input
s = "rabbbit", t = "rabbit"
Output
3
Explanation
As shown below, there are 3 ways you can generate "rabbit" from s.

Python solution

PythonSolution
class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        m, n = len(s), len(t)
        f = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(m + 1):
            f[i][0] = 1
        for i, a in enumerate(s, 1):
            for j, b in enumerate(t, 1):
                f[i][j] = f[i - 1][j]
                if a == b:
                    f[i][j] += f[i - 1][j - 1]
        return f[m][n]

Complexity

Time
O(m × n)
Space · auxiliary
O(m × n)

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 115. Distinct Subsequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0940Distinct Subsequences IIHard
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0044Wildcard MatchingHard
0072Edit DistanceMedium

Frequently asked questions

How hard is LeetCode 115. Distinct Subsequences?

LeetCode 115. Distinct Subsequences is rated Hard on LeetCode.

What is the time complexity of LeetCode 115. Distinct Subsequences?

The Python solution on this page runs in O(m × n).

What is the space complexity of LeetCode 115. Distinct Subsequences?

The Python solution on this page uses O(m × n) auxiliary space.

What topics does LeetCode 115. Distinct Subsequences cover?

LeetCode 115. Distinct Subsequences is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.