Top 150 InterviewMedium

Distinct Subsequences

Detailed guide and Python implementation for the 'Distinct Subsequences' problem.

Problem Statement

Medium

Given two strings s and t, return the number of distinct subsequences of s which equals t.

A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Write a function numDistinct(s: str, t: str) -> int.

Constraints
  • 1 <= len(s), len(t) <= 1000
  • s and t consist of English letters

Examples

Example 1
Input
s = "rabbbit", t = "rabbit"
Output
3
Explanation

There are 3 ways you can generate "rabbit" from s: **rab**b**bit**, **ra**b**bbit**, **rab**bb**it**.

Example 2
Input
s = "babgbag", t = "bag"
Output
5
Explanation

There are 5 ways you can generate "bag" from s.

Need a Hint?
Consider using 2D DP-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.