SDE & MLE Prep

115. Distinct Subsequences

Problem

Count the distinct ways to pick a subsequence of s (a set of positions) that spells t.

Example: s = "rabbbit", t = "rabbit" → 3; s = "babgbag", t = "bag" → 5

Constraints: lengths ≤ 1000; the answer fits in 32 bits.

dp[i][j] = ways s[:i] contains t[:j] as a subsequence = dp[i−1][j] (skip s[i−1]) + dp[i−1][j−1] if chars match. 1-D: iterate j downward.

Complexity: O(m·n) time, O(n) space.

class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        dp = [1] + [0] * len(t)
        for ch in s:
            for j in range(len(t), 0, -1):
                if t[j - 1] == ch:
                    dp[j] += dp[j - 1]
        return dp[-1]