Distinct Subsequences — LeetCode 115 Python Solution

HardStringDynamic Programming
Problem
#115
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

Python
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

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

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

On a study list

This problem is on NeetCode 150.

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 \times n).
What is the space complexity of LeetCode 115. Distinct Subsequences?
The Python solution on this page uses O(m \times 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.

Get Stealth Interview